Let's keep it simple...
class Client
abstract class AbstractBusinessObject
class BusinessObject
class BusinessObjectFactory
Okay, so your Client needs to perform some operations on AbstractBusinessObject . Obviously somewhere one BusinessObject instance needs to be created. Why not in the client? What's the harm?
Let's assume you convinced me to create new BusinessObjects in my BusinessObjectFactory. Great. Now the factory has to do the heavy lifting. Let's assume my factory has a Create(DataRow row) method because my BusinessObject needs the DataRow to extract useful information from it.
My BusinessObject's properties are {get; private set;}. Therefore I cannot assign any property values in my factory. Probably I shouldn't anyway.
This however means I have to pass along the DataRow entirely. So basically the factory just passes along my parameter. What's the use of the factory here?
Ok so I might have different implementation of BusinessObject - each of them having different constructors. I guess it makes sense for the factory to know how to construct any specific BusinessObject then. But then again I need a specific factory to get a specific BusinessObject. At least all examples I saw suggest just that. ConcreteFactoryB creates ConcreteProductB (ConcreteFactoryA creates ConcreteProductA) How does the client know how to construct the factory? Or even which one to create?
Ah the factory is injected... composition root. Right. But I could have injected the BusinessObject directly just as well.
The example over at DoFactory made it a little bit more clear I think. Is it all about making sure the Lion doesn't eat Bisons? And the Wolf doesn't feed on Wildebeests? If that's all the factory tries to assure I don't need one if I just want to create a single object, right?
So does a factory like this one here make any sense? Does a factory ever make sense if I only have one Create() method which only makes one type of classes?
Really, I read a lot about it.
Every example looks like the other. I'm missing the point :( Can anyone provide a crystal clear real world example?
https://stackoverflow.com/a/2280289/1407618
Been there, done that...
You are a Person using an AbstractComputer. You do not care about the make of the computer, as long as it has all the basic stuff an AbstractComputer have. Now, in order to use a computer, would you Create() one yourself or would you get it from a ComputerStore or ComputerProvider? Those are going to give you the computer that best fits your needs (i.e. your budget, skills, screen size). They got their AbstractComputer shipped from a ComputerFactory that knows how to Create them best.
As for the properties of your AbstractComputer, some make it possible to swap the Storage and some don't. It really depends on your context. But for your factory to put them inside the computer, they needed an entry point (constructor) if they are not swappable after it is constructed.
The important point is that it is not the responsibility of the AbstractComputer to know how to constructs himself given the pieces. Nor it is the responsibility of the Consumer to know which make of computer it needs (they sometimes can, if they have enough knowledge and that their needs will never ever change).
(It looks like you accept the idea that dependency injection is (often) useful, so I'll base my answer on that assumption.)
If an instance of A depends on an instance of B, and you already have the B instance, then you should indeed inject it into the A instance without using a factory. However, factories are useful in these situations:
Lazy loading: You don't have the B at the time you create the A, so A needs to create its own B (without knowing exactly what type B is, and possibly without knowing (all) of B's dependencies).
Optional loading: In some situations, loading B might not even be necessary, and whether it is necessary or not must be determined by A.
Multiple instances: A might need to create multiple instances of B whenever it wants to do so.
As usual, no pattern is a silver bullet, so there are many situations in which factories or dependency injection are overkill. Your questioning of the usefulness of factories is good, and will probably lead to you only using the pattern when it's actually beneficial.
Related
I have a Business Layer, whose only one class should be visible to outer world. So, I have marked all classes as internal except that class. Since that class requires some internal class to instantiate, I need other classes to be marked as public and other classes depend on some other classes and so on. So ultimately almost all of my internal classes are made public.
How do You handle such scenarios?
Also today there is just one class exposed to outer world but in future there may be two or three, so it means I need three facades?
Thanks
Correct, all of your injected dependencies must be visible to your Composition Root. It sounds like you're asking this question: Ioc/DI - Why do I have to reference all layers/assemblies in entry application?
To quote part of that answer from Mark Seeman:
you don't have to add hard references to all required libraries. Instead, you can use late binding either in the form of convention-based assembly-scanning (preferred) or XML configuration.
Also this, from Steven:
If you are very strict about protecting your architectural boundaries using assemblies, you can simply move your Composition Root to a separate assembly.
However, you should ask yourself why doing so would be worth the effort. If it is merely to enforce architectural boundaries, there is no substitute for discipline. My experience is that that discipline is also more easily maintained when following the SOLID principles, for which dependency injection is the "glue".
After doing a lot of research I am writing my findings, so that it may be of some help to newcomers on Dependency Injection
Misunderstandings regarding my current design and Dependency Injection:
Initial approach and problem(s) associated with it:
My business layer was having a composition root inside it, where as
it should be outside the business layer and near to the application
entry point. In composition root I was essentially having a big factory referred as Poor Man's DI by Mark Seemann. In my application starting point, I was creating an instance of this factory class and then creating my only (intended to be) visible class to outside world. This decision clearly violates Liskov's Principle which says that every dependency should be replaceable. I was having a modular design, but my previous approach was tightly coupled, I wasn't able to reap more benefits out of it, despite only some code cleanliness and code maintainability.
A better approach is:
A very helplful link given by Facio Ratio
The Composition root should have been near the application root, all dependency classes should be made public which I referred initially as a problem; making them public I am introducing low coupling and following Liskov's substitution which is good.
You can change the public class to the interface and all other parts of the program will only know about the interface. Here's some sample code to illustrate this:
public interface IFacade
{
void DoSomething();
}
internal class FacadeImpl : IFacade
{
public FacadeImpl(Alfa alfa, Bravo bravo)
{
}
public void DoSomething()
{
}
}
internal class Alfa
{
}
internal class Bravo
{
}
I can see three solutions, none real good. You might want to combine them in someway. But...
First, put some simple parameters (numeric, perhaps) in the constructor that let the caller say what he wants to do, and that the new public class instance can use to grab internal class objects (to self-inject). (You could use special public classes/interfaces used solely to convey information here too.) This makes for an awkward and limited interface, but is great for encapsulation. If the caller prefers adding a few quick parameters to constructing complex injectable objects anyway this might work out well. (It's always a drag when a method wants five objects of classes you never heard of before when the only option you need, or even want, is "read-only" vs "editable".)
Second, you could make your internal classes public. Now the caller has immense power and can do anything. This is good if the calling code is really the heart of the system, but bad if you don't quite trust that code or if the caller really doesn't want to be bothered with all the picky details.
Third, you might find you can pull some classes from the calling code into your assembly. If you're really lucky, the class making the call might work better on the inside (hopefully without reintroducing this problem one level up).
Response to comments:
As I understand it, you have a service calling a method in a public class in your business layer. To make the call, it needs objects of other classes in the business layer. These other classes are and should be internal. For example, you want to call a method called GetAverage and pass it an instance of the (internal) class RoundingPolicy so it knows how to round. My first answer is that you should take an integer value instead of a class: a constant value such as ROUND_UP, ROUND_DOWN, NEAREST_INTEGER, etc. GetAverage would then use this number to generate the proper RoundingPolicy instance inside the business layer, keeping RoundingPolicy internal.
My first answer is the one I'm suggesting. However, it gives the service a rather primitive interface, so my second two answers suggest alternatives.
The second answer is actually what you are trying to avoid. My thinking was that if all those internal classes were needed by the service, maybe there was no way around the problem. In my example above, if the service is using 30 lines of code to construct just the right RoundingPolicy instance before passing it, you're not going to fix the problem with just a few integer parameters. You'd need to give the overall design a lot of thought.
The third answer is a forlorn hope, but you might find that the calling code is doing work that could just as easily be done inside the business layer. This is actually similar to my first answer. Here, however, the interface might be more elegant. My first answer limits what the service can do. This answer suggests the service doesn't want to do much anyway; it's always using one identical RoundingPolicy instance, so you don't even need to pass a parameter.
I may not fully understand your question, but I hope there's an idea here somewhere that you can use.
Still more: Forth Answer:
I considered this a sort of part of my first answer, but I've thought it through and think I should state it explicitly.
I don't think the class you're making the call to needs an interface, but you could make interfaces for all the classes you don't want to expose to the service. IRoundingPolicy, for instance. You will need some way to get real instances of these interfaces, because new IRoundingPolicy() isn't going to work. Now the service is exposed to all the complexities of the classes you were trying to hide (down side) but they can't see inside the classes (up side). You can control exactly what the service gets to work with--the original classes are still encapsulated. This perhaps makes a workable version of my second answer. This might be useful in one or two places where the service needs more elaborate options than my first answer allows.
We are working on two product lines that will share the same code.
For functionality that differs, I have both product lines implement the same interface (or base classes in some case) and these types will be created in the Main class (which is separate for both product lines) and passed further downstream.
For code that is deep inside the business logic, it is very hard to have product line specific code. We do not want to user if(ProductLine == "ProductLine1") and else methodology.
So I am planning to implement a Factory class which will have static methods to return NewObject1(), NewObject2() and so on. This Factory class will be registered in the Main class as Factory.RegisterClient(ProductLine1).
So with the above approach, the factory(which internally contains ProductLine1Factor & ProductLine2Factory) knows which type of objects to create.
Do you know a better approach to this problem. Please note that ProductLine1 was already existing and ProductLine2 is something new (but is 90% similar to ProductLine1). We cannot do drastic refactoring such that both product lines exist. We want to do as minimally invasive code changes as possible.
The factory approach typically exposes an interface, but the problem with interfaces is that I cannot expose static types which are also needed.
I would really appreciate if some experts would shed some light.
Your approach sounds fine.
Instead of a custom crafted factory, why don't you use a fully fledged IoC framework like NInject or Unity? You could have the service implemented twice, for each client, and select one in a container configuration file, statically. This way you don't even need to change the single line of your code if you add yet another implementation, you just reconfigure i.e. make some changes in the xml file.
Anyway, an IoC container is just a tool, use it or not, it just replaces your factory (IoC containers are sometimes called "factories on steroids").
I don't know if this actually qualifies as DI, since I'm not talking about injecting a concrete implementation of an abstract dependency. I'm just talking about injecting stuff that's needed period.
In my game engine, I want to clean up the part that handles the state of the game (menu, stage select, in-game, cutscenes, etc). All of these things implement a common interface. But one of them, in-game, is also referenced specifically as the current level being played.
There are right now 43 references in my project to the current level, as accessed through the game, a singleton. For example, Game.CurrentGame.CurrentMap.Something. The references are in screens, entities, behavior components, even in the main form (for debugging tools).
I want to get rid of this reference by injecting everything that's needed. But the CurrentMap itself isn't the desired dependency - other things are being accessed below it. So my initial plan is to go into each place, find the thing that's actually being used, and inject it by adding a parameter to that class constructor. This introduces another dependency one level up, so I repeat the process until everything is finished. But the problem with this is it will introduce a lot more constructor parameters, including in places that aren't using the dependency directly. A lot of classes will wind up accepting a dependency just so they can pass it on to another object below them.
What would be a cleaner alternative to this?
You are talking about a scenario where the dependencies must make their way down through a few layers of objects to get where they are really needed. This does not need to happen.
If an object creates dependencies itself you end up with this problem. If objects are given the dependencies it needs by a factory or DI container (which is just a fancy factory) then you will not have this problem. So to avoid this problem, you need to decide if each class is concerned with game logic or creating classes.
Let's say you have object a, which calls object b, which calls object c and object c needs the current level and object b does not.
The wrong way to do it is to call new C(level); from within b. As you have pointed out, b does not need to know about the level so it seems things are getting worse not better. You have not gone far enough with the dependency injection. Instead of creating c within b, just ask for c in the constructor of b. Now class b only knows about c and knows nothing about level.
Misko has explained this better than I can here http://misko.hevery.com/2009/03/30/collaborator-vs-the-factory/
Code in the factory looks like this:
Level level = new Level();
C c = new C( level );
B b = new B( c );
A a = new A( b );
The class B only knows about it's direct collaborators (c) and has no dependency on Level. Because we are creating things in the factory, it is not necessary to pass the leaves of the object graph down through the object graph.
If class B had the responsibility for creating c then it needs to know all about how to make an instance of class c. This is wrong.
Look at using a DI Framework, like Castle Windsor, Structuremap or Unity (there are plenty of others that are perfectly solid as well).
The problem you are describing is not the only problem that these frameworks solve, but it's a big part of the type of friction that they almost completely eliminate.
The fact that the dependencies are concrete implementations and not higher level abstractions is irrelevant. See this question (asked by yours truly):
IOC/DI: Is Registering a Concrete Type a Code Smell?
Usually I inject a service that keeps track of the current state:
public interface IGameStateTracker
{
Game CurrentGame {get;}
GameMap CurrentMap {get;}
}
You should only have to inject this service in constructors of classes that will need it directly. I'm afraid I don't fully understand why you're finding that you need to inject things into classes that don't directly need it: this may be a sign that you're not using proper DI patterns. Could you provide some code samples to show an example of this problem?
I second Phil Sandler's point about using a DI framework. It will make life much easier. But it won't make up for using incorrect DI patterns in the first place.
More specifically, What's the best approach for classes where state matters, within an application which implements Dependency Injection.
Say I need access to an object that's in a particular state. For example, this object might have been initiated in a different thread, or by a process I have no control over.
A good example of an object like this that already exists in .NET is the HttpContext.
In this case, Microsoft decided to go with the Static approach, so I just say:
var currentObj = HttpContext.Current;
And this gives me a particular instance of an object without having to worry where it came from.
The problem with the Static approach is that it doesn't play very nicely with dependency injection.
The other option is to configure your certain class as a Singleton in your IoC Container. This means that you can inject it, and depending on the current IoC Container config it'll be the correct instance of the class.
However, the downfall of this approach is that the stateful importance of the object is no longer explicit in the code, it's not obvious by looking at it. With the Static class used to access and instance it's more clear that the state is important. Maybe that doesn't matter though.
So, is there a pattern that helps me out here?
Context:
For context, I'm working on an application which has many instances of a class performing IO operations. They exists within their own threads.
I want to be able to interact with those objects (background tasks) via a web interface, so a Controller. I want to be able to interrogate them, and manipulate them etc.
Update:
Sorry, I think my use of the term "stateful" is a bit misleading. let me explain some thing:
"state" is probably the wrong word. I mean communicating with an object whereby I don't have control over it's lifecycle.
It is funny that I use "stateful" when talking about static classes. That's why I gave the HttpContext example, as that exactly what it does. The Current property gets you a very specific instance, not any new instance.
When I say that static doesn't play nice with DI, I meant, you can't inject Static classes. I could create a wrapper, yes, but I'm just pushing the problem elsewhere no?
I should have been more clear about my definition of Singleton. I meant a Singleton lifestyle, as defined in an IoC Container.
I always prefer Singleton over static. In fact, I almost never use statics in my own classes.
True singletons and static classes are both very difficult to write automated tests against. Do you mean a single instance looked up at runtime? That would make sense to me but I don't know the right construct to use in C#. The analog in Java is JNDI.
Neither or both. Presuming the stateful dependency is thread-safe the better approach is to build at least a basic layer of abstraction around said dependency then inject said abstraction into your classes. Singleton vs static becomes pretty immaterial then.
so in my application I've got several different customers being "serviced". Each customer has their own implementations of various classes that are all based on interfaces.
With the latest customer being added, I've noticed there will be a lot of duplication of code from another customer but the other customer is in no other way related to them.
I've already got a default implementation for several other customers and roll new ones as i need them.
My question is how do i refactor this and still keep the code clean? If i were a dev new to this code base i would want each customer to either use the default or their own implementation of these classes... but that's a lot of duplication.
Consider using an abstract base class with abstract or virtual members. Abstract members are essentially equivalent to interface members (they have no build-in behavior, they only guarantee the method exists) whereas virtual members have a default implementation which can be overridden by derived classes.
Your question is really too vague to answer in full, but here's how you can leverage inheritance.
If you want all classes to use the same implementation of a member then that member can be implemented in the base-class.
If you want each class to have its own implementation of a member then you can either use a base-class with abstract members, or an interface.
If you want some classes to use the same implementations and others to use different implementations then implementing the default behavior in the base-class and override it as needed.
My main point is that OOP there is a spectrum of how much or little functionality is in base/abstract/concrete classes. There's no silver-bullet answer, sometimes your base classes will be skeletons and sometimes they'll be fully fleshed-out; it all depends on the specific problem at hand.
Is there some way that you could create a base class, then a specific implementation for each customer and then using some type of Dependency Injection have that load classes or functionality as needed. You want to really have a DRY system so as to avoid headaches and typos or other similar human mistakes.
You may use either inheritance (put common logic to the base class) or aggregation (spread that logic among other classes and make use them from your customers).
I'd recommend the visitor pattern:
http://en.m.wikipedia.org/wiki/Visitor_pattern
As well as the mediator pattern:
http://en.m.wikipedia.org/wiki/Mediator_pattern
Reason being that it sounds like you may benefit from decoupling, or at least more-loose-coupling, the business logic from your classes, based on what you are saying.
It's a bit difficult to know what to suggest without a better understanding of the code... but some things that have worked for me in similar situations include:
Use a Strategy, for the duplicated code. I've had most success where the strategy is encapsulated within a class implementing a known interface (one class per alternate strategy). Often in such cases I use some form of Dependency Injection framework (typically StructureMap) to pass the appropriate strategy/strategies to the class.
Use some sort of template class (or template methods) for the common item(s).
Use a Decorator to add specific functionality to some basic customer.
STW suggested that I should offer some clarification on what I mean by "Strategy" and how that differs from normal inheritance. I imagine inheritance is something you are very familiar with - something (typically a method - either abstract or virtual) in the base class is replaced by an alternate implementation in the derived class.
A strategy (at least the way I typically use it) is normally implemented by a completely different class. Often all that class will contain is the implementation for a single replaceable operation. For example if the "operation" is to perform some validation, you may have a NullValidationStrategy which does nothing and a ParanoidValidationStrategy which makes sure every McGuffin is the correct height, width and specific shade of blue. The reason I usually implement each strategy in its own class is because I try and follow the Single Responsibility Principle which can make it easier to reuse the code later.
As I mentioned above, I typically use a Dependency Injection (DI) framework to "inject" the appropriate strategy via the class constructor, but a similar results may be obtained via other mechanisms - e.g. having a SetSomeOperationStrategy(ISomeOperation StrategyToUse) method, or a property which holds the strategy reference. If you aren't using DI, and the strategy will always be the same for a given customer type, you could always set the correct choices when the class is constructed. If the strategy won't be the same for each instance of a given customer type, then you probably need some sort of customer factory (often a factory method will be sufficient).
I'd go with the answer of spinon (got my vote at least), but it's to short so let me elaborate:
Use your interfaces for the default implementation and then use dependency injection. Most tools allow you to define a scope or some criteria how to resolve something.
I assume that you do know the client at some early point of the program. So for ninject you just might want to define a "Module" for each client and load that into the kernel, depending on the client.
So I'd create a "no customization" Module and create a "ClientX" Module for every special case that uses ´Bind.To()` instead.
You end up with
a base implementation that is clean/default
a single place change for a new client (got a new one? Great. Either it works with the default or just needs a single Module that maps the interfaces to other classes)
The rest of the code shouldn't mind and get the dependencies via injection (constructor, property, whatever is easiest to go for. Constructor would probably be the nicest way) and has no special treatment at all.
You could even use a conditional binding in Ninject link text to solve the binding issue without different modules at all (although, depending on the number of clients, this might get messy and should better be separated).
I was going to suggest aggregation, as #the_joric suggests, over inheritance, but your description makes it sound like your application is already reasonably well-factored - that there aren't a lot of small classes waiting to be extracted from your existing classes. Assuming that's the case, for any given interface, if you have a perfect class for the new customer already written and ready to go, I would say go ahead and use it. If you're worried about that, for some reason, then take that perfect class, make it abstract, and create empty subclasses for your existing customer and your new customer - and if it's not quite a perfect fit, then that's the way I would go.