Factory Pattern In Dependency Injection - c#

I have a class that looks like such:
public class SomeRepo : ISomeRepo
{
private IThingFactory _thingFactory;
public class SomeRepo (IThingFactory thingFactory)
{
_thingFactory = thingFactory;
}
public IThing GetThingFromDatabase(int id)
{
string thingName = /* some call that gets back some primitives */
IThing returnVal = _thingFactory.createThing(thingName);
return returnVal;
}
}
So in short, SomeRepo is a repo that is responsible for communicating with some datastore to get an IThing by Id. And IThingFactory is a simple factory that returns a new IThing given a string property.
If I am using a Dependency Injection container, should I still be relying on an IThingFactory? It seems like I am mixing the two design patterns for the sake of convenience. Is there a more elegant way to construct an IThing without the need of a factory or is what I have a good pattern to follow?
Thanks
EDIT: The DI container I am using is Ninject.

If IThink is a class that does not need more than the output from the database (so if it need nothing from the DI container) and you dont want to mock it for testing, IMHO you could create the class by calling the constructor.
Otherwise the factory pattern is the right choise in my eyes.
For NInject, there is a factory extension that makes is very easy to create factories - You have just to create the interface and the extension creates the corresponding implementation at runtime.

Dependency injection is technique to achieve loose coupling between layers, not exactly what i would describe as a design pattern.
There is nothing wrong with mixing design patterns or using multiple techniques as a general thing to state, unless you are introducing complexity where it is not needed.
So my suggestion is that you approach things by questioning your requirement and understanding the use of design patterns and then you would be able to recognize the need to use a certain pattern to make your code maintainable, extensible or whatever technical requirement you are trying to fulfill.
Questions i would ask myself:
What is the problem i am trying to tackle ?
How extensible is this logic going to be ? what are the moving parts and what are the core requirements ?
Which design pattern tackles this kind of issue ?
You also need to weigh between the complexity introduced into the code and time consumed by using certain design patterns and the benefits of using it on short as well as the long run ?

Related

Dependency Injection: what do you lose when instantiating concrete classes in parameterless constructor

Generally speaking, my dependencies are abstracted to interfaces, but I will only be using one concrete implementation during non-testing use. For example, were I to write a FooService:
public class FooService : IFooService
{
private readonly IBarDependency _barDependency;
public FooService(IBarDependency barDependency)
{
this._barDependency = barDependency;
}
public FooService() : this (new BarDependency())
{
// nothing to do here
}
. . . // code goes here
}
Now purists tend to gasp in horror, because I instantiated a concrete class in the parameterless constructor. I have, in the past, shrugged this off, because I know the only time I will not be using the concrete class is when I am unit testing and mocking dependencies.
While it does couple the FooService class to the BarDependency class, it's not a tight coupling; these classes and interfaces also exist in the same assembly, so it doesn't seem to me like I'm losing a whole lot here, or painting myself into a corner. I can still easily test the FooService class without getting unmanageable code, just by using the constructor that allows me to pass in mocked interfaces.
So the question is: what is actually at risk here? What am I losing with this sort of pattern that is worth adding an IoC container?
Lifetime management, for example. Maybe you use BarDependency throughout your code and only want one instance to be alive. You can't do this if every user creates their own instances.
You also have to find all usages of new BarDependency() if you ever want to replace it with new NewBarDependency().
A container fixes both problems for you, as then you configure the instantiation and lifecycle of objects in one method, namely where you set up your container.
It depends, but if the FooService needs to be accessed by some other developer, the dependency to BarDependency will be basically hidden. In my opinion not only mocking and testing is the reason for using dependency injection, but also a clear indication what is used by certaing classes, and what they are need to work properly.
And maybe I'm to much purist, but when such pattern is ok, then it's easily to go further and end up with a totally tightly coupled and hard maintanable code.
What you lose without dependency injection is the ability to centralize all aspects of the dependency management. Visualizing the dependency graph and managing the lifecycles of your objects is easier when you have all the information in one place, instead of scattered all over the code.
A concrete example would be if you wanted to replace the default implementation of IBarDependency used in some, but not all of the classes. Reasoning about which ones to replace is much easier if the dependencies are all wired in the same file or group of files.

Dependency Injection - What to do when you have a lot of dependencies?

I have a class A that depends on 10 other classes. According to Dependency Injection pattern, i should pass all dependencies of A by its constructor.
So lets assume this constructor (of course this is not a working or real code, since I am not allowed to post the real code here)
public ClassA(ClassB b, ClassC c, ClassD d, ClassE e, ClassF f, ClassG g, ClassH h, ClassI i) {
this.b = b;
this.c = c;
this.d = d;
this.e = e;
this.f = f;
this.g = g;
this.h = h;
this.i = i;
}
I have read on Martin Fowler's book about refactoring that having a method with a lot of parameters is a code smell and should not happen.
My question is: is this OK when we are talking about DI? Is there a better way of inject dependencies without breaking Martin Fowler's rules?
I know I could pass the dependencies through properties, but that may cause errors since no one is really sure what should be pass in order that the class works.
EDIT
Thanks for all your answers. I will try now to demonstrate some of class A dependencies:
1 - A class to access a DB
2 - Another class to access another DB (yes, i need to perform operations on two databases)
3 - A class to send error notifications by email
4 - A class to load configurations
5 - A class that will act as timer for some operations (maybe this one can be avoided)
6 - A class with business logic
There any many others that i am trying to get rid of, but those are really necessary and I dont see any ways of avoiding them.
EDIT
After some refactoring now i have 7 dependencies (down from 10). But I have 4 DAO objects:
CustomerDAO
ProcessDAO
ProductsDAO
CatalogDAO
Is it correct do create another class called MyProjectDAO and inject those DAOS onto it? This way I will have only one DAO class that aggregates all DAO objects of my project. I dont think this is a good idea because it violates the Single Responsibility Principle. Am I right?
In my experience:
Try to design your class so it needs fewer dependencies. If it needs that many, it may have too many responsibilities.
If you're really convinced that your class design is appropriate, consider whether it may make sense for some of those dependencies to be joined together (e.g. via an adapter which takes responsibility for one "big" operation your class needs by delegating to a few of the dependencies). You can then depend on the adapter instead of the "smaller" dependencies.
If every other bit really makes sense, just swallow the smell of having a lot of parameters. It happens sometimes.
Can you justify (to yourself) why the class depends on 10 other classes? Are there member variables you use to tie together a subset of those classes? If so, that indicates that this class should be broken up so that the extracted class would depend on the subset and the variables that tie such state together goes in the extracted class. With 10 dependencies, it's possible that this class has simply grown too large and needs to have its internals broken up anyway.
A note regarding your final sentence: such order dependency can also be a code smell, so it's probably good not to expose it in your interface. In fact, consider whether or not the order requirements are because operations need to be carried out in a specific order (it is the complexity of the algorithm or protocol), or because you've designed your classes to be inter-dependent. If the complexity is due to your design, refactor to eliminate the ordered dependency where possible.
If you cannot refactor (the complexities are all essential and you just have a terrible coordination problem on your hands), then you can abstract the ugliness and keep users of this class shielded (builder, factory, injector, etc).
Edit: Now that I have thought about it, I am not convinced that essential complexities of your algorithm or protocol cannot be abstracted a bit (though that might be the case). Depending on your specific problem, similarities in the manipulations of those dependent classes might either be better solved with the Strategy pattern or the Observer pattern (event listeners). You might have to wrap these classes in classes that adapt them to slightly different interfaces than what they currently expose. You'd have to evaluate the tradeoff of having the code in this monster class become more readable (yay) at the expense of up to 10 more classes in your project (boo).
I'd also like to make an addendum to abstracting the construction of this class. It seems important that any class that depends on this class also use the Dependency Injection pattern. That way, if you do use a builder, factory, injector, etc. you don't accidentally rob yourself of some of the benefits of using the DI pattern (the most important in my mind is the ability to substitute mock objects for testing).
Edit 2 (based on your edit):
My first thought is "what, no logging dependency?" :)
Even knowing what the dependencies are, it's difficult to offer useful advice.
First: what are the responsibilities of everyone? Why does this class depend on controller code (the business logic) and on Model code (two different database access classes, with DAO classes)?
Depending both on DAOs and DB access classes is a code smell. What is the purpose of a DAO? What is the purpose of the DB classes? Are you trying to operate at multiple levels of abstraction?
One of the principles of OO is that data and behavior get bundled into little things called classes. Have you violated this when you created this business logic class distinct from the objects it manipulates distinct from the DAO distinct from this class? Related: Take a brief diversion into SOLID.
Second: A class to load configurations. Smells bad. Dependency Injection helps you identify dependencies and swap them out. Your monster class that depends on certain parameters. These parameters are grouped into this configuration class because...? What is the name of this configuration class? Is it DBparameters? if so, it belongs to the DB object(s), not to this class. Is it generic like Configurations? If so, you've got a mini dependency injector right there (granted, it is probably only injecting string or int values instead of composite data like classes, but why?). Awkward.
Third: The most important lesson I learned from Refactoring was that my code sucked. Not only did my code suck, but there was no single transformation to make it stop sucking. The best I could hope for was to make it suck less. Once I did that, I could make it suck less again. And again. Some design patterns are bad, but they exist to allow your sucky code to transition to less sucky code. So you take your globals and make them singletons. Then you eliminate your singletons. Don't get discouraged because you've just refactored to find that your code still sucks. It sucks less. So, your Configuration loading object may smell, but you might decide that it isn't the smelliest part of your code. In fact, you may find that the effort to "fix" it isn't worth it.
Yes - a method taking this many parameters should be considered a code smell. Is this method truly only doing one thing and one thing only?
If this is still true you can still lower the number of dependencies by looking at the relationships between the dependencies - are any of them closely related, could they be coupled into aggregate dependencies? E.g. you could refactor by creating a new class K that uses A, B and C internally (injected into class K by constructor, then using composition) - so the number of parameters to the method would be reduced by two.
Rinse and repeat until aggregating doesn't make sense anymore and/or you have a reasonable number of parameters.
Also see a related blog post: "Refactoring to Aggregate Services"
I'd also advise to redesign your application. In case it is not possible you can pass your IoC container as a constructor parameter. If you do not want to couple your code with a concrete implementation you can always abstract it. The code will look something like this.
public interface IAbstractContainer
{
T Resolve<T>();
}
public class ConcreteContainer: IAbstractContainer
{
private IContainer _container; // E.g. Autofac container
public ConcreteContainer(IContainer container)
{
_container = container;
{
public T Resolve<T>()
{
return _container.Resolve<T>();
}
}
public classA(IAbstractContainer container)
{
this.B = container.Resolve<ClassB>();
this.C = container.Resolve<ClassC>();
...
}
}
A ConcreteContainer instance is injected the usual way.

Should concrete objects always be returned by a factory method when using an interface?

When using interfaces, where exactly should the hard implementation of each object be retrieved from. Is that done by creating a factory object for each type?
IRepository<User> userRepository = new UserRepository(connection); // Needs a dbconnection
userRepository.Create(user);
//Is this the best way?
IRepository<User> userRepository = RepositoryFactory.GetUserRepository(connection);
public static class RepositoryFactory
{
public static IRepository<User> GetUserRepository(DbConnection connection)
{
return new UserRepository(connection);
}
}
What is the best of most logical way to get a UserRepository object to work with? If I used a factory object for UserRepository, do I pass in the connection object or what is that process?
I'm sorry if I read your question incorrectly but you might want to take a look at
Inversion of Control and Dependency Injection and see how those would fit best for what you are trying to do.
IoC: http://visualstudiomagazine.com/articles/2010/08/01/inversion-of-control-patterns-for-the-microsoft-net-framework.aspx / http://joelabrahamsson.com/entry/inversion-of-control-introduction-with-examples-in-dotnet
Dependency Injection: http://www.blackwasp.co.uk/DependencyInjection.aspx
As John said you can use IOC. But that only is valid if you think you would like to have that extra layer of decoupling in your application. It would also make stubbing out/mocking a lot easier if you use an IoC. But I know that sometimes introducing a new moving piece into your project can be a pain.
The factory would indeed be a way to go. I would pass in a high level abstraction into the factory. A string or an enum that says something like as "FromADatabase" or "FromANetwork". Its up to the factory to look up the appropriate construction details for what you want (from a configuration file for example), construct the required concrete object and pass it back.
So as far as the consumers are concerned, they go to a factory and say something very high level such as I need something from there, that does this. Its up to the factory to figure out how to create that a concrete implementation of what is being asked and pass it to the caller.

Help designing a order manager class

So I have an order manager class that looks like:
public class OrderManager
{
private IDBFactory _dbFactory;
private Order _order;
public OrderManager(IDBFactory dbFactory)
{
_dbFactory = dbFactory;
}
public void Calculate()
{
_order.SubTotal
_order.ShippingTotal
_order.TaxTotal
_order.GrandTotal
}
}
Now, the point here is to have a flexible/testible design.
I am very concerned about being able to write solid unit tests around this Calculate method.
Considerations:
1. Shipping has to be abstracted out, be loose coupled since the implementation of shipping could vary depending on USPS, UPS, fedex etc. (they have their own API's).
2. same goes with calculating tax
Should I just create a Tax and Shipping Manager class, and have a tax/shipping factory in the constructor? (exactly how I have designed my OrderManager) class?
(the only thing that I can think of, in terms of what I am "missing", is IoC, but I don't mind that and don't need that extra level of abstraction in my view).
Well, you are already moving towards dependency injection in your approach, so why not go the whole hog and use some sort of IoC container to handle this for you?
Yes, if you want it abstrated out, then create a separate class for it. If you want to truly unit test what is left, abstract out an interface and use mock testing. The problem is, the more you abstract out like this, the more plumbing together there is to do and the more you will find yourself wishing you were using an IoC framework of some kind.
You are suggesting constructor injection, which is a common approach. You also come across property injection (parameterless constructor, set properties instead). And there are also frameworks that ask you to implement an initialization interface of some kind that allows the IoC framework to do the initialization for you in a method call. Use whatever you feel most comfortable with.
I do think an IOC would help with the plumbing of instantiating the correct concrete classes but you still need to get your design the way you want it. I do think you need to abstract away the shipping with an interface that you can implement with a class for each of your shippers (USPS, UPS, FEDEx, etc) and could use a Factory class (ShippingManager) to pass the correct one out or depend on the IOC to do that for you.
public interface IShipper
{
//whatever goes into calculating shipping.....
decimal CalculateShippingCost(GeoData geo, decimal packageWeight);
}
You could also just inject an IShipper and ITaxer concrete classes into your OrderManager and you calculate method just calls into those classes....and can use an IOC nicely to handle that.
Just a thought:
Your Calculate() method taking no parameters, returning nothing and acting on private fields is not how I would do it. I would write it as a static method that takes in some numbers, an IShippingProvider and an ITaxJurisdiction and returns a dollar total. That way you have an opportunity to cache the expensive calls to UPS and your tax tables using memoization.
Could be that I'm prejudiced against public methods that work like that. They have burned me in the past trying to bind to controls, use code generators, etc.
EDIT: as for dependency injection/IOC, I don't see the need. This is what interfaces were made for. You're not going to be loading up a whole array of wacky classes, just some implementations of the same weight/zipcode combo.
That's what I would say if I were your boss.
I would take the Calculate method out into a class. Depending on your circumstances OrderCalculator might need to be aware of VAT, Currency, Discounts, ...
Just a thought.

Is this Factory Method creation pattern?

I have been using factory method creation pattern for awhile now. I was just recently told that this:
public static class ScheduleTypeFactory
{
public static IScheduleItem GetScheduleItem(ScheduleTypeEnum scheduleType)
{
IScheduleItem scheduleItem = null;
switch (scheduleType)
{
case ScheduleTypeEnum.CableOnDemandScheduleTypeID:
{
scheduleItem = new VODScheduleItem();
break;
}
case ScheduleTypeEnum.BroadbandScheduleTypeID:
{
scheduleItem = new VODScheduleItem();
break;
}
case ScheduleTypeEnum.LinearCableScheduleTypeID:
{
scheduleItem = new LinearScheduleItem();
break;
}
case ScheduleTypeEnum.MobileLinearScheduleTypeID:
{
scheduleItem = new LinearScheduleItem();
break;
}
}
return scheduleItem;
}
}
is not a factory method creation pattern by my "Tech" lead without telling me why or giving me her interpretation. I kindly asked for an explanation and she told me she didn't have time. I was told to just rename it. If I am wrong, then I will no doubt accept that I have implemented this incorrectly for years. Is this how YOU would implement the factory method creation pattern? Thanks in advance.
I would agree to call the method a "Factory Method", though the design is not strictly a "Factory Method Pattern".
Here is a key point (from Wikipedia):
...The Factory method lets a class defer instantiation to subclasses."
Since your class is static and method static (hence non-virtual), there is no "deferring" possible.
Conceptually, notice also, that this implementation, though provides encapsulation, does not decouple/delay any decision.
Having said that, same Wikipedia article does present this schema as a variant of the "Factory Method Pattern".
Summary of the Summary: In my opinion this snippet is not a proper implementation of the "Factory Method OO Design Pattern", since it does not satisfy "a class defer instantiation to subclasses." Though, personally I would freely refer to this solution as "factory method".
To make it real factory method pattern, you need to allow the method to be overridden by subclasses. I.e. factory class (ScheduleTypeFactory) needs to be extensible (i.e. non-static), and GetScheduleItem needs to be virtual.
Sure looks like the factory pattern to me. I don't see anything wrong with your implementation.
From Factory method pattern:
The essence of the Factory Pattern is
to "Define an interface for creating
an object, but let the subclasses
decide which class to instantiate. The
Factory method lets a class defer
instantiation to subclasses."
This is exactly what you are doing.
As a side note: a good rule of thumb is that whenever someone tells you something and is unable or unwilling to provide a rationale for their statement, there is a good chance they are unqualified to make the statement at all.
Yes this is a factory pattern. My only comment would be that you fail silently for enum values that you don't specifically handle. That may be expected but I like to add the following to the end of statements like that
default:
throw new InvalidOperationException("Invalid Enum Value");
Your code fragment is what in Head First Design Patterns is called "The Simple Factory" (p. 117).
The main difference to the Factory Method Pattern is the ConcreteCreator (compare the diagram in the upper right corner), which is a simple class in your case. In the "real pattern" the factory class is abstract with an abstract factory class. So, there is one more abstraction level. However, for many use cases, your Simple Factory is enough.
Simple Factory
Simple Factory http://yuml.me/7221a4c9
Factory Method Pattern
Factory Method Pattern http://yuml.me/3d22eb4e
I think it is traditionally called the simple factory pattern to distinguish it from the 'real' Abstract Factory pattern. It might be that you are not adhering to some sort of internal naming practice. She really ought to explain herself though.
Your lead is right (sorry for the formatting, but this answer need some of it in order to be seen between the main line that is stating the lead is a moron): neither by the GOF book nor Head First this a factory method.
GoF :
“Define an interface for creating an
object, but let the subclasses decide
which class to instantiate. Factory
Method lets a class defer
instantiation to subclasses.”
In your example, it's not a subclass that is deciding.
Have you implemented it incorrectly all these years? No, you just haven't implemented the factory pattern, but what is sometimes referred to as the 'Simple Factory Pattern', which probably has done the job just fine.
Looks like a (basic) factory to me... in many factories the implementation is more complex (perhaps involving types resolved at runtime), but that is not (AFAIK) a requirement. The only other critique I'd have added is to combine the cases, and do something more dramatic if you don't recognise the type...
I'm surprised so many saying that this is the factory pattern.
(So chances are that I'm thinking of this wrong, so please let me know.)
It looks to me like what you have there is only a part of the design. If you call it from your client, it's referred to as a "simple" factory, but it's not really considered a design pattern. (Don't get me wrong, I do this all the time).
The factory design pattern would state that your factory inherits/implements an abstract factory/factory interface.
Then, in your class which needs to use the factory (the client), you set the type of the factory to the abstract/interface, creating a concrete factory:
i.e. --> IFactory factory = new ConcreteFactory();
The concrete factory would then create your IScheduleItem (leaving it to the factory to actually create the concrete type).
In the end I think the whole point is about loose coupling. While a "simple" factory loosely couples the construction of the product from the client, it does not decouple the factory. The factory pattern also decouples the factory.
Then again, it's early, I haven't had coffee, and I have a nasty habit of posting absolutely horrible responses that miss the entire point of the question.
Well, Wikipedia says it is a factory method:
public class ImageReaderFactory
{
public static ImageReader getImageReader( InputStream is )
{
int imageType = figureOutImageType( is );
switch( imageType )
{
case ImageReaderFactory.GIF:
return new GifReader( is );
case ImageReaderFactory.JPEG:
return new JpegReader( is );
// etc.
}
}
}
Looks like a factory pattern to me. Tell your tech lead you don't have time to explain why she is wrong.
That is the Factory pattern, but it's not necessarily the most maintainable variant. A more maintainable variant would maintain some sort of global map between ScheduleTypeEnum values and actual concrete subtypes of IScheduleItem -- that way, you could replace the switch statement with a lookup of the map.
Why is it more maintainable? Because subclass authors can add pairs to the map at the site where they derive the class, rather than in the GetScheduleItem() factory function itself. Hence the latter never needs updating; it is constantly up-to-date.
In C++ you can do this using a global std::map -- for each concrete subclass, the author of the subclass adds a dummy global variable which actually just registers the class (by adding to the map) in its constructor, which runs at program startup time. I'm certain that there's a convenient way to do the same thing in C#.
(C++ guru Herb Sutter has an entertaining description here, but it's fairly C++-heavy.)
It is indeed a "factory" in that you have a method that returns a specific instance of the IScheduleItem based on some sort of logic; however, it probably isn't the best implementation or the most maintainable given that you are using a switch statement.
Yup, that's the factory pattern alright. Your Tech lead is wrong.
Looks like a basic factory pattern to me. I'm curious to hear why your tech lead doesn't think this is a pattern.
I'm also dissapointed she wouldn't take the time to explain things. Having been a tech lead before on a team, it is curcial to take the time to explain your decisions.
It is the factory method pattern, at least according to Wikipedia:
http://en.wikipedia.org/wiki/Factory_method_pattern
What the tech lead is likely thinking is that the Factory pattern is to replace a constructor in the same object, not to return subclasses, or perhaps only return subclasses from a superclass, not from an unrelated object. It's wrong, but that is probably the thinking.
The fact that Wikipedia lists your pattern as an example shows that it is correctly a factory pattern. The patterns were defined to provide a common language for common solutions, so clearly if Wikipedia is showing this as an example, it is part of the common language. An academic debate about what the "Factory Pattern" is in some abstract sense misses the point of patterns.
Take back the power right now! Just drop 'Type' from the wording. ScheduleFactory FTW. Wait, is this a factory for 'Schedules' or 'ScheduleItems'? If it's scheduleitems then the factory should be called 'ScheduleItemFactory'. Be expressive!!!
The simplest explanation of the factory pattern, which I learned from a patterns and practice class, was that if you rely on another class to create the instances of your class, then you're using the factory pattern.
Of course, often times you want to add a layer of indirection by making your class abstract or an interface.
This is very simplified view of it, but either way, you are using the factory pattern.
Your Tech is right on renaming the method:
public static IScheduleItem GetScheduleItem(ScheduleTypeEnum scheduleType)
The action of the method is not to get something, is to create something.
How do you decide which scheduleType should be created? Seems that logic should
be encapsulated not the switch of the type.
Also why the static on the class? Where are you using it from?
public class ScheduleTypeFactory
{
public static IScheduleItem createScheduleFrom(ScheduleTypeEnum scheduleType)
{
switch (scheduleType)
{
case ScheduleTypeEnum.CableOnDemandScheduleTypeID:
case ScheduleTypeEnum.BroadbandScheduleTypeID:
return new VODScheduleItem();
case ScheduleTypeEnum.LinearCableScheduleTypeID:
case ScheduleTypeEnum.MobileLinearScheduleTypeID:
return new LinearScheduleItem();
}
raise InvalidSchedule;
}
}
Thats a textbook Factory Pattern.
Some texts call it a Simple Factory Patteren, but I've never seen any criteria for what "Simple" means.
In my practice, a Factory Pattern is any intelligent creation of a concrete class coresponding to a desired interface.
But why fight your tech lead over naming a method. Rename it, move on with your life.

Categories