I have a (growing) list of Data-Generators. The generator that I need is created by a factory class. The generators all implement a common Interface, which includes among other things a static string name.
What I would like to do: Call the factory.Create method with a string parameter for the above mentioned name. The create method finds the generator with this name and returns a new instance of said generator.
Bonus in my opinion of this way to do it: I only have to add new generator classes without having to edit the factory.
Question:
Is this a good way to handle this problem?
How can I find all generators? Reflection over every implementation of the interface/every member of the namespace (unique for the generators + their interface)?
Is it correct to call this way of working a factory, or is this some different pattern?
In the end I would call the factory like this (simplified):
//Caller
public DataModel GetData2()
{
var generator = new DataFactory().Create("Gen.2");
return generator.GetData();
}
//Factory
public class DataFactory
{
public AbstractDataGenerator Create(string type)
{
//Here the magic happens to find all implementations of IDataGenerator
var allGenerators = GetImplementations();
var generator = allGenerators.FirstOrDefault(f => f.name == type);
if (generator != null)
return (AbstractDataGenerator)Activator.CreateInstance(generator);
else
return null;
}
}
//Interface
public abstract class AbstractDataGenerator
{
public static string name;
public abstract DataModel GetData();
}
//Data-Generators
public class DataGen1 : AbstractDataGenerator
{
public static string name = "Gen.1";
public DataModel GetData()
{
return new DataModel("1");
}
}
public class DataGen2 : AbstractDataGenerator
{
public static string name = "Gen.2";
public DataModel GetData()
{
return new DataModel("2");
}
}
Should the magic GetImplementations() in the factory be done via Reflection or somehow different? Should I use a completely different approach?
Since answers refer to IoC and DI: This project uses NInject already, so it would be available.
Switched from interface to abstract class.
Is this a good way to handle this problem?
Having a factory to get an instance of the logic class you need by some key - I believe it is a good way. It is a pattern that I use a lot myself. About the way you have your key - I'd prefer to not have it as a static member (regardless to the fact that interfaces can't have static members) but just as a property and to add a base class to the IDataGenerator. That base class will have a constructor that will get the name - That way each new DataGenerator you create will have to set it and you wont forget.
About having the name as a string - I personally prefer having it "strongly typed". What I mean is that if I pass Gen . 2 instead of Gen.2 with strings I will discover this problem only in runtime. Possible other ways (if you want, because a simple string is fine too - a matter of taste):
Replace strings with an enum
Have a static class with static readonly strings for all your values - then in your code use those values. You get the benifits of the intellisense and of not getting the string wrong but better than enum - you can just still pass strings that are not in the "list" so you can add new ones as add-ons.
Have a RequestGenerator object, with each Generator being IDataGenerator<TGeneratorRequest>. This might be an overkill but if you have also extra information you need for the creating of a DataGenerator which differs between them then consider it .
How can I find all generators? Reflection over every implementation of the interface/every member of the namespace (unique for the generators + their interface)?
Yes, reflection can be a good way to do so. However, I would suggest to read into Dependency Injection and IoC Containers like Castle Windsor for example. There are things out there that already implement it for you, so why to re-invent the wheel :)
DI is a life changer concept in my opinion
Is it correct to call this way of working a factory, or is this some different pattern?
Yap. It is a Factory
Should the magic GetImplementations() in the factory be done via Reflection or somehow different?
See answer for question 2
This is where constructor injection can REALLY shine. Look into dependency injection tools and employ one! It also checks your "Bonus" request.
Here's what your factory might look like with constructor injection:
public class DataFactory
{
private Dictionary<string, IDataGenerator> generators;
public DataFactory(IDataGenerator[] generatorReferences)
{
this.generators = generatorReferences
.ToDictionary(k => k.name, v => v);
}
public IDataGenerator Create(string type)
{
IDataGenerator generator = null;
this.generators.TryGetValue(type, out generator);
return generator;
}
}
Most DI software has the capability to automatically scan assemblies for implementations of a certain type (e.g. IDataGenerator) and register those with itself, when it constructs an instance of your DataFactory it'll automatically include them.
Related
I am not overly familiar with implementing lambdas and expressions, but I've used to this syntax many times in MVC where the lambda is identifying a property on an object:
Html.Label(model => model.Foo)
In my app I am using Ninject conditional bindings to supply the instance of the Settings class which is injected when I request an instance of Class. My Class looks like this:
public class Class
{
private readonly Settings settings;
public Settings Settings { get { return settings; } }
public Class(Settings settings)
{
this.settings = settings;
}
}
I have some code which looks like this to get an instance of Class. I am aware this is the service locator anti pattern, but we have no choice in this case due to other constraints:
var settings = new Settings();
var instance = Ioc.Instance.Get<Class>("settings", settings);
I would like to refactor it to look like this so that it is strongly typed, using a lambda to specify which argument on the constructor I am supplying:
var settings = new Settings();
var instance = Ioc.Instance.Get<Class>(x => x.settings, settings);
So, is this possible, and what would the code look like?
Conceptually there is a lack of the factory (factory interface), so it should be introduced to avoid using the container directly.
The Ninject Factory (factory interface) extension could be used to create the instance, as follows:
Declare a factory interface:
public interface IFactory
{
Class Create(Settings settings);
}
Add a binding to the composition root:
kernel.Bind<IFactory>().ToFactory();
Use the factory to get an instance:
var settings = new Settings();
var factory = Ioc.Instance.Get<IFactory>();
var instance = factory.Create(settings);
Please see the ninject/ninject.extensions.factory for the alternatives.
The problem with constructor argument names and expressions is, that an expression is only valid / complete when it covers all parameters of the constructor. Now i suppose you want to inject a few of the parameters (have ninject handle them) and for one or two specific parameters you want to pass a value, let's say it looks like:
public interface IFoo { }
public class Foo : IFoo
{
public Foo(IServiceOne one, IServiceTwo two, string parameter) {...}
}
Ninject supports ctor expressions, but only for bindings, and they work like this:
IBindingRoot.Bind<IFoo>().ToConstructor(x =>
new Foo(x.Inject<IServiceOne>(), x.Inject<IServiceTwo>(), "staticArgument");
so instead of only specifying the "staticArgument" which you are interested in, you also have to specify IServiceOne and IServiceTwo. What if the constructor changes? Well the call needs to be adapted as well! Lot of work for just passing a single simple parameter.
Now if you still want to do this i'd suggest having a look at the ToConstructor code and creating a similar extension for a Get call which will translate some call
IResolutionRoot.Get<IFoo>(x =>
new Foo(
x.Ignore<IServiceOne>(),
x.Ignore<IServiceTwo>(),
x.UseValue("mystring"));
to
IResolutionRoot.Get<IFoo>(new ConstructorArgument("parameter", "mystring"));
However, i would suggest going with #Sergey Brunov 's answer and use Ninject.Extensions.Factory. Now I think your going to say that it's no good because you'll still have to specify the parameter name,.. which is not refactor safe and a hassle (no code completion...).
However, there's a solution to the problem: Instead of using a constructor argument which "matches" the name of the argument, you can use a type matching argument.
Ok, there's a catch. If you've got multiple arguments of the same type,.. well it won't work. But i think that's seldomly the case and you can still introduce a container data-class to address it:
public class FooArguments
{
string Argument1 { get; set; }
string Argument2 { get; set; }
}
Now how can you use type matching?
There's two ways:
Use a Func<string, IFoo> factory. Just inject Func<string, IFoo> into where you want to create and IFoo.
Extend the Factory extension. Yes you've heard right ;-) It's actually not that difficult. You "just" need to implement a custom IInstanceProvider (also see http://www.planetgeek.ch/2011/12/31/ninject-extensions-factory-introduction/) so you can something like:
public interface IFooFactory
{
IFoo Create([MatchByType]string someParam, string matchByName);
}
(==> use an attribute to tell the factory extension how to pass the parameter to the Get<IFoo>request).
Look at following article -
http://handcraftsman.wordpress.com/2008/11/11/how-to-get-c-property-names-without-magic-strings/
Specifically
public static class Extensions
{
public static string GetPropertyName<T,TReturn>(this Expression<Func<T,TReturn>> expression)
{
MemberExpression body = (MemberExpression)expression.Body;
return body.Member.Name;
}
}
Note - This method may not work for all possible ways in which one can use expressions to indicate a property name for a class, and hence may need to be enhanced based on your needs (how generic you need it to be).
But essentially, once you have this helper method, your call becomes
var settings = new Settings();
Ioc.Instance.Get<Class>(GetPropertyName(x => x.settings), settings);
I have a service layer that retrieves a DTO from a repository. Depending on a property in that DTO I need to use one of two strategies to perform calculations on the DTO. I have created a factory to return the appropriate strategy and I'm using a DI container (Munq) to instantiate the object.
public class CalculationFactory
{
private readonly IDependencyResolver _resolver;
public CalculationFactory(IDependencyResolver resolver)
{
ThrowIfNullArgument(resolver, "resolver", typeof(IDependencyResolver));
_resolver = resolver;
}
public static ICalculation CreateCalculator(int serviceType)
{
switch (serviceType)
{
case 1: return _resolver.Resolve<ICalculation>("Type1");
case 2: return _resolver.Resolve<ICalculation>("Type2");
default: return _resolver.Resolve<ICalculation>("InvalidType");
}
}
}
This requires me to pass in the dependency resolver when I instantiate the factory so that it can be used to resolve/instantiate the appropriate calculation to use. Is this the correct approach? If I want to add a new type of calculation then I would need to update the factory CreateCalculator method and register the new type.
Update (long)
I'm not really getting traction on the suggestions I'm afraid. I've gone back to my copy of Mark's DI in .Net and specifically chapter 6 on refactorings. So I have a class MeterReadings and I need to calculate a charge using one of two calculations based on a runtime value. I add an abstract factory to the mix but in my concrete factory I still need to new up the appropriate calculation. I feel like I'm missing the point here:
public enum ServiceType
{
Actuals = 1, CopyBlock,
}
public interface IChargeCalculator
{
decimal CalculateCharge();
}
public interface IChargeCalculatorFactory
{
IChargeCalculator CreateChargeCalculator(ServiceType serviceType);
}
public class MeterReading
{
private readonly IChargeCalculatorFactory chargeCalculatorFactory;
public MeterReading(IChargeCalculatorFactory chargeCalculatorFactory)
{
if (chargeCalculatorFactory == null)
throw new ArgumentNullException("chargeCalculatorFactory");
this.chargeCalculatorFactory = chargeCalculatorFactory;
}
}
public class ConcreteChargeCalculatorFactory : IChargeCalculatorFactory
{
public IChargeCalculator CreateChargeCalculator(ServiceType serviceType)
{
switch (serviceType)
{
case ServiceType.Actuals : return new ActualsChargeCalculator();
default: return new CopyBlockChargeCalculator();
}
}
}
But in my container I can register the different calculators and if I pass in the container as the concrete factory I get something like the following (not tested) which frankly looks fairly reasonable to me. Any feedback/clarification would be welcome.
Container.Register<IChargeCalculator>("Actuals",
c => new ActualsChargeCalculator());
Container.Register<IChargeCalculator>("CopyBlock",
c => new CopyBlockChargeCalculator());
...
public enum ServiceType
{
Actuals = 1, CopyBlock,
}
public interface IChargeCalculator
{
decimal CalculateCharge();
}
public class MeterReading
{
private readonly IDependencyResolver chargeCalculatorFactory;
private ServiceType serviceType;
public MeterReading(IDependencyResolver chargeCalculatorFactory)
{
if (chargeCalculatorFactory == null)
throw new ArgumentNullException("chargeCalculatorFactory");
this.chargeCalculatorFactory = chargeCalculatorFactory;
}
public decimal Charge
{
get
{
return chargeCalculatorFactory.Resolve<IChargeCalculator>(serviceType.ToString());
}
}
}
Yes, I would say you are doing it in a proper way.
Though you write that you need to "pass in the dependency resolver ", is there a reason that you can't have the factory class injected into the class where it is needed? Then the factorys dependency on the dependency resolver should be resolved by the dependency resolver itself (to itself).
I hope that sentence made sense.
I have tried to come up with a "cleaner" solution, but have not found any yet. A solution similar to what is suggested in the question (which is not exactly the same) Dessus links is certainly possible, but I really see that as just moving the same code to another place. Remo also writes that it could be done in a factory class instead of a factory method.
It's a bit like deciding between writing a lampda or a helper class. It mostly comes down to readabilty, and for me a factory method is just to big, and having it in a module initializer or bootstrapper seams to disorganized.
BTW I can recommend Ninject, it is a really good, clean DI. Plus it's documentation uses Ninja examples ;)
I believe this question has been answered here, where it is suggested you use meta data against your bindings and create bindings for each implementation. You then use a binding to pull the meta data to choose which binding to use: Ninject conditional binding based on property value . Possibly this may or may not be possible with Munq? Not sure.
The person (Remo) who answered that question is one of the architects of ninject, and is very knowledgeable. I believe that his answer should hold alot of weight. (I am a basing this of being a subscriber to the ninject mailing list, and seeing him answer about half of all the questions).
Is this a good pattern? It has a code smell to me with having a factory class aware of the IUnityContainer...
My basic need was to resolve an ICalculationRuleProcess at runtime depending on an Id of a class. It could be based on something other than the Id, I am aware of that... basically I have a known set of Ids that I need to deal with because I bootstrapped the records into the database manually and there is no way to edit the records. With each Id I have a related class. I also have a varying number of constructor parameters within each class that implements the ICalculationRuleProcess, so using an IoC container is extremely helpful versus some crazy switch statement and variable constructor aguments using Activator.CreateInstance
Here is what I did:
Registered the IUnityContainer instance within the container itself. I wasnt sure if this was even possible, but it worked.
Registered all of the ICalculationRuleProcess classes with a unique identifier within the registration (basically just the Id.ToString() of each possible DistributionRule)
Created a factory to determine the correct ICalculationRuleProcess, and had it use the IoC container to figure out the correct class to load.
Registered the factory class (ICalculationRuleProcessFactory) to the IoC container
Wherever the ICalculationRuleProcess needed to be used, I had the class take an ICalculationRuleProcessFactory in its constructor and have it call the Create method to figure out which ICalculationRuleProcess to use.
The code for the factory is here:
public interface ICalculationRuleProcessFactory
{
ICalculationRuleProcess Create( DistributionRule distributionRule );
}
public class CalculationRuleProcessFactory : ICalculationRuleProcessFactory
{
private readonly IBatchStatusWriter _batchStatusWriter;
private readonly IUnityContainer _iocContainer;
public CalculationRuleProcessFactory(
IUnityContainer iocContainer,
IBatchStatusWriter batchStatusWriter )
{
_batchStatusWriter = batchStatusWriter;
_iocContainer = iocContainer;
}
public ICalculationRuleProcess Create( DistributionRule distributionRule )
{
_batchStatusWriter.WriteBatchStatusMessage(
string.Format( "Applying {0} Rule", distributionRule.Descr ) );
return _iocContainer.Resolve<ICalculationRuleProcess>(
distributionRule.Id.ToString() );
}
}
This seems okay to me, given the constraints you described. The most important thing is that all of your rules implement ICalculationRuleProcess and that all consumers of those rules only know about that interface.
It isn't inherently bad that your factory takes the container dependency, especially as an interface. Consider that if you ever had to change container implementations, you could create an IUnityContainer implementation that doesn't use Unity at all (just forward all the members of the interface to their corresponding methods in the replacement container).
If it really bothers you, you can add yet another layer of indirection by creating an agnostic IoC interface with the requisite Register, Resolve, etc. methods and create an implementation that forwards these to Unity.
There is another way you can achieve this without factory taking dependency on IUnityContainer, which is not inherently bad in and of itself. This is just a different way to think about the problem.
The flow is as follows:
Register all different instances of ICalculationRuleProcess.
Get all registered ICalculationRuleProcess and create a creation lambda for each one.
Register ICalculationRuleProcessFactory with a list of ICalculationRuleProcess creation lambdas.
In ICalculationRuleProcessFactory.Create return the right process.
Now the tricky part of this is to preserve the Ids that the registrations were made under. Once solution is to simply keep the Id on the ICalculationProcess interface, but it might not semantically belong there. This is where this solution slips into ugly (which is more of a case of missing functionality in Unity). But, with an extension method and a small extra type, it looks nice when it's run.
So what we do here is create an extension method that returns all registrations with their names.
public class Registration<T> where T : class {
public string Name { get; set; }
public Func<T> CreateLambda { get; set; }
public override bool Equals(object obj) {
var other = obj as Registration<T>;
if(other == null) {
return false;
}
return this.Name == other.Name && this.CreateLambda == other.CreateLambda;
}
public override int GetHashCode() {
int hash = 17;
hash = hash * 23 + (Name != null ? Name.GetHashCode() : string.Empty.GetHashCode());
hash = hash * 23 + (CreateLambda != null ? CreateLambda.GetHashCode() : 0);
return hash;
}
}
public static class UnityExtensions {
public static IEnumerable<Registration<T>> ResolveWithName<T>(this UnityContainer container) where T : class {
return container.Registrations
.Where(r => r.RegisteredType == typeof(T))
.Select(r => new Registration<T> { Name = r.Name, CreateLambda = ()=>container.Resolve<T>(r.Name) });
}
}
public class CalculationRuleProcessFactory : ICalculationRuleProcessFactory
{
private readonly IBatchStatusWriter _batchStatusWriter;
private readonly IEnumerable<Registration<ICalculationRuleProcess>> _Registrations;
public CalculationRuleProcessFactory(
IEnumerable<Registration<ICalculationRuleProcess>> registrations,
IBatchStatusWriter batchStatusWriter )
{
_batchStatusWriter = batchStatusWriter;
_Registrations= registrations;
}
public ICalculationRuleProcess Create( DistributionRule distributionRule )
{
_batchStatusWriter.WriteBatchStatusMessage(
string.Format( "Applying {0} Rule", distributionRule.Descr ) );
//will crash if registration is not present
return _Registrations
.FirstOrDefault(r=>r.Name == distributionRule.Id.ToString())
.CreateLambda();
}
}
//Registrations
var registrations = container.ResolveWithName<ICalculationRuleProcess>(container);
container.RegisterInstance<IEnumerable<Registration<ICalculationRuleProcess>>>(registrations);
After I wrote this I realised that this is more creative lambda douchebaggery than a architecturally pretty solution. But in any case, feel free to get ideas out of it.
Hey Rob, I'm intending to use essentially the same pattern. I've got multiple types of shopping cart item that need to be associated with their own specific set of validator instances of varying class.
I think there is a smell about this pattern and its not that the factory has a reference to the IoC container, its that typically, an IoC container is configured in the application root which is typically the UI layer. If a crazy custom factory was created just to handle these associations then possibly it should be in the domain.
In short, these associations are possibly not part of the overall program structure that's set up before the application runs and so shouldn't be defined in the application root.
I am struggling to understand what my factory class should do in my DDD project. Yes a factory should be used for creating objects, but what exactly should it be doing. Consider the following Factory Class:
public class ProductFactory
{
private static IProductRepository _repository;
public static Product CreateProduct()
{
return new Product();
}
public static Product CreateProduct()
{
//What else would go here?
}
public static Product GetProductById(int productId)
{
//Should i be making a direct call to the respoitory from here?
Greener.Domain.Product.Product p = _repository.GetProductById(productId);
return p;
}
}
Should i be making a direct call to the repository from within the factory?
How should i manage object creation when retriving data from a database?
What do i need to make this class complete, what other methods should i have?
Should i be using this class to create the Product object from the domain and repository from right?
Please help!
Should i be making a direct call to
the repository from within the
factory?
No, don't use a factory when your retrieving stuff, use a factory only when you are creating it for the first time.
How should i manage object creation
when retriving data from a database?
Pass that data into the factory, if it is required for the object's initial creation.
What do i need to make this class
complete, what other methods should i
have?
Many factories are not even individual classes, they are just methods that provide object creation. You could fold the factory method into another class, if you felt like it was just going to call a parameterless constructor.
Should i be using this class to create
the Product object from the domain and
repository from right?
The repository is for getting (in a sense creating) existing objects, the factory is for the first time you create an object.
Initially many factories won't do much except call a constructor. But once you start refactoring and/or creating larger object hierarchies, factories become more relevant.
Explanation and Example:
For instance, in the project I'm working on I have an excel processor base class and many subclasses implementing that base class. I use the factory to get the proper one, and then call methods on it, ignorant of which subclass was returned.(Note: I changed some variable names and gutted/altered a lot of code)
Processor base class:
public abstract class ExcelProcessor
{
public abstract Result Process(string ExcelFile);
}
One of the Processor subclasses:
public class CompanyAExcelProcessor : ExcelProcessor
{
public override Result Process(string ExcelFile)
{
//cool stuff
}
}
Factory:
public static ExcelProcessor CreateExcelProcessor(int CompanyId, int CurrentUserId)
{
CompanyEnum company = GetCompanyEnum(CompanyId);
switch (company)
{
case CompanyEnum.CompanyA:
return new CompanyAExcelProcessor();
case CompanyEnum.CompanyB:
return new CompanyBExcelProcessor();
case CompanyEnum.CompanyC:
return new CompanyCExcelProcessor(CurrentUserId);
//etc...
}
}
Usage:
ExcelProcessor processor = CreateExcelProcessor(12, 34);
processor.Process();
Be carefull, there are two reasons to instantiate a new object : Creating it and rehydrating it from the database.
The first case is handled by the factory. You can provide several methods to create an object on the factory.
Factory methods should return valid objects, so you can pass parameters to these methods to provides required information.
The factory method can also chose the actual type to instantiate based on parameters.
You should not mix this with rehydrating from the database. This kind of instantiation should take values from the datarow and instantiate the object with it. I usualy call this a data builder instead of a factory.
The main difference is that the factory will instantiate an object with a new identity while the databuilder will instantiate an object with an already existing identity.
What should go in your factory's Create method is whatever is necessary to put a brand spanking new object into a VALID state.
Now, for some objects that means you won't do anything except this:
public Product Create()
{
return new Product();
}
However, you may have business rules, default settings, or other requirements that you want to enforce when an object is created. In that case, you would put that logic in that method.
And that's part of the benefit of the Factory. You now have one and only one place where that special logic resides, and only one place where a new object gets created.
I personally would use the factory in couple of circumstances:
1) Something elsewhere governs what type of objects this factory returns (ie. it can return objects depending on circumstances. For example return a stub object when I am testing, return an actual implementation when I am not (this is obviously more of Inversion of Control / Dependency Injection issue - but if you do not want to add containers to your project just yet)).
2) I have quite complex objects that have containers, dependencies, other relation etc. and they need to be built carefully to avoid creating null or meaningless references. For example if I have a Schedule object I may need some start, end date fields set - if the logic for retrieving, figuring out these date is complex enough I may not want the calling class to know about it and just call the default factory method that created the schedule object.
Hope this helps.
In the example given above, I'm a little unclear on the distinction between your factory and the repository. I wonder if you shouldn't simply add CreateProduct as a method to the repository, and using DI to push the repository into code that needs it? If the factory isn't doing anything, etc...
Or if you just want it to act as a globally registered repository, perhaps something like:
public static IFooRepository Default {get;private set;}
public static void SetRepository(IFooRepository repository) {
Default = repository;
}
(in my mind it seems clearer to separate the "set" in this case, but you don't have to agree)
and have the callers use var product = YourFactory.Default.CreateProduct(); etc
#ThinkBeforeCoding - in #m4bwav's example, the factory is getting a valid ID from a helper method, but it's not creating a new record in a persistence layer anywhere. If, however, I'm using a database auto-generated identity column as my identities, it seems like a factory would have to call into the repository to do the initial object creation. Can you comment on which method is "correct"?
In the builder you can have any logic you need to inforce the invariants on your entites, a little example using Java as development language...
I have a User entity that has a username, a password and an email, all attributes required so I have:
public class User {
private String username;
private String password;
private String email:
/**
* #throws IllegalArgumentException if the username is null, the password is null or the
* email is null.
*/
public User(final String theUsername, final String thePassword, final String theEmail) {
Validate.notNull(theUsername);
Validate.notNull(thePassword);
Validate.notNull(theEmail);
this.username = theUsername;
this.password = thePassword;
this.email = theEmail;
}
// Getters / Setters / equal / hashCode / toString
}
and then I have the UserBuilder:
public class UserBuilder {
private String username;
private String password;
private String email;
public UserBuilder withUsername(final String theUsername) {
Validate.notNull(theUsername);
this.username = theUsername;
return this;
}
public UserBuilder withPassword(final String thePassword) {
Validate.notNull(thePassword);
this.password = thePassword;
return this;
}
public UserBuilder withEmail(final String theEmail) {
Validate.notNull(theEmail);
this.email = theEmail;
return this;
}
public User build() {
User user = new User(this.username, this.password, this.email);
return user;
}
}
And you can use the builder like this:
UserBuilder builder = new UserBuilder();
try {
User user = builder.withUsername("pmviva").withPassword("My Nifty Password").withEmail("pmviva#somehost.com").build();
} catch (IllegalArgument exception) {
// Tried to create the user with invalid arguments
}
The factory's solely purpose is th create valid instances of objects. In order not to duplicate creation and hydration code you can have your repositories to query a rowset from the database and delegate the creation of the object to a builder passing the rowset's data.
Hope this helps
Thanks
Pablo
I'm writing some tests, and frequently I find myself having to look up generic parameters to pass explicitly pass along.
public class MyService : SecureService<RootEntity>
{
//Intentionally omitted does not provide information related to question
}
public DepedencyReplaceScope<IContextProvider> CreateMockScope<TRootEntity>
{
var mockCtx = Mock.Of<IContextProvider>(x => x.WriteContext<TRootEntity> == new FakeContext<TRootEntity>())
return new DependencyReplaceScope(mockCtx);
}
Currently when I'm creating mocks for my test, I have too go into the service and find out what it's root is to pass along. However, It would be a lot nicer if I could create a scope based on the service.
e.g (pseudo code)
public DepedencyReplaceScope<IContextProvider> CreateMockScopeFromService<TService>
where TService : SecureService<>
define TRootEntity : TService<()>
{
return CreateMockScope<TRootEntity>();
}
This won't work since I don't think there is a way to define a proxy for the Generic. Is there a way to create this scope solely from the TService (I don't want to use reflection directly to build it, but I don't mind using a hack with a moq since it abstracts the reflection)
The best thing I was able to come up so far was:
public static class MockScopeProvider
{
public static DepedencyReplaceScope<IContextProvider> CreateMockScopeFromService<U>(SecureService<U> dummy)
{
// your logic....
var mockCtx = Mock.Of<IContextProvider>(x => x.WriteContext<U>() == new FakeContext<U>());
return new DependencyReplaceScope(mockCtx);
}
}
With usage being like that:
MockScopeProvider.CreateMockScopeFromService(default(MyService));