I've been searching for guidance for using IoC containers in domain driven design. Evan's book unfortunately doesn't touch on the subject. The only substantial guidelines I could find on the internet is here.
Many of Malovic's points are common sense but I'm concerned about a few of them. He suggests that IoC container's should be reserved for resolving services only and that using an IoC container to resolve domain dependencies is a bad idea. However, he doesn't back up this assertion with any examples. He simple states it as a matter of fact.
He then goes on to say that mixing IoC containers and factories doesn't make sense. This appears to contradict his first point. If, in fact, domain dependencies shouldn't be resolved by an IoC container how then should they be resolved? Evan's book clearly points to factories as the logical choice.
I would appreciate any input you have on the matter. I'm a novice when it comes to both DDD and IoC. I'm struggling to grasp how IoC and DDD can work together.
In my opinion he is correct about not using IoC container in domain model. That practice I follow myself as well. Basic idea is that services may contain infrastructure dependencies and therefore its wise to mock them. Domain entities don't have those, so its not important to mock them up (still coding to interfaces is good practice).
Factories for domain entities should not be in IoC container, but factories for services should. Basically you may reference entity factories in your services. It's not very tight coupling.
Good reading about IoC can be found at Billy McCafferty's blog post "Dependency Injection 101"
IOC containers are invaluable when designing unit-testable code and are orthogonal to DDD. You could create your own implementation of factory and builder patterns if you want...by why go through the trouble?
Absolutely. Use an IOC container that's just powerful enough to meet you specific requirements; no more, no less.
We use DDD, and dependency injection (the pattern), but do not use a dependency injection framework.
One problem with popular dependency injection frameworks is how they separate configuration into XML files. XML is a great markup language. How it became a configuration language, I will never understand. The issue, of course, is that you have to run the application before you know if everything is wired up correctly. It is also hard to see what code is used where. If you are using interfaces, then the only reference to an implementation will be in an XML file, which is harder to spot. And finally you lose type safety and generics. (I once saw a horrible bug in production which would have been caught by the compiler had we not been using XML.)
I should point out that I am not saying that dependency injection is bad. It is a fundamental pattern of good object design. But there is absolutely nothing wrong with doing wiring in a factory.
At my last two projects we have removed large amounts of "code" out of XML files, and into factories. The factories are wired up with container managed services (such as JDBC connections, JMS connections and so forth). The application has become much simpler to understand, because the factory is less verbose than XML. And as a Java programmer, it is much easier to wire together a program using control-space, instead of XML twiddling - and your IDE will highlight when you have broken something.
In an integration test, just create the objects as you would in a factory.
ie,
dbConnection = DatabaseConnectionFactory.connection();
serviceUnderTest = new PaymentProcessor(new CustomerRepository(connection));
Related
Ironically, the problem DI is trying to solve, is exactly the problem that has been created in the project. Are there any resources for using the framework where i'm capable of picking and choosing which features I want to use/enable and those i want to omit?
It's very hard to manage dependencies and develop a modular and well-structured application without using dependency injection techniques.
Which i strongly disagree with; and believe to be the opposite, as there are plenty of cases where it's common without DI than with it.
Currently, i'm stuck on trying to use the project by calling all of the classes manually, as the DI is broken and constantly prone to errors, with vague or unhelpful exceptions being thrown and preventing app from executing. I'm unable to properly and thoroughly debug it, and that isnt the kind of assistance i'm seeking.
Strictly the question being posed is, i want to use the framework without using dependency injection, are there solutions; if yes, can you provide them in the form of step-by-step, or copy-paste? Can i use the framework without it, or am i tasked with writing my own because it's unable to keep it's functions modular?
My solution so far, is i'm attempting to restructure, the entire framework to remove the DI logic from the foundation of the framework (it's coupled inside [root] functions instead of beside them?); but i'm not sure if there are ways around it, and if possible to just strictly not use it if i dont want it enabled.
I've already created a repository class that's based on interface, then i've made some changes to a few manager classes that use the repository... but then there's stores, other managers (repetitive layers stacked inside each other), cache (not sure why it's layered into foundation), UoW (dont need this, cant null it out), publishers (dont know how to pull this one out), and a whole bunch of other, logic inside logic, that dont need to be structured the way the project is layered. The whole thing feels more like a Jenga tower, than a flexible framework where isolation of responsibilities is at core of development practice.
EDIT
Related StackOverFlow Problems:
AspNet Core3 Identity configuration
What i've attempted:
Multiple Identities in ASP.NET Core 2.0
ASP.NET Identity without Entity Framework
How to resolve generic interface to generic implementation when using dependency injection?
How to implement Unit Of Work pattern with Dapper? (used this to make Abp.UoW interface nullable, but there's still other areas of forced UoW logic in-between functions in core layers of framework)
Basically, any search results containing "without dbcontext", "without entityframework", "without dependency injection", "using dapper", that all contained "asp identity" were search queries i was using.
Before modification and after modifications (attempts at using my own app services and domain model) all yielded
An error occurred while starting the application.
AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity...
which is basically dependency injection breaking, and not being clear as to what the issue is, besides... "you cant use this class that inherits interface/abstract class that's referenced throughout framework and by DI." So i prefer not to use DI, and work around it, since solutions arent reliable to resolving my issues.
I hope I don't sound to pedantic, but your "without DI example" is still an example of DI. You apply constructor injection, which is a form of DI. What I understand is that you want to apply Pure DI instead of using the built-in DI Container. There are advantages of using Pure DI of using a DI Container, which is, for instance, described in:
When to use a DI Container by Mark Seemann,
When should you use a container? by me,
and about three quarters of our book on DI focuses on applying DI by hand, i.e. Pure DI.
Now for the bad news...
When working with ASP.NET Core (and most of the framework that depends on the .NET Core DI Container), you can never completely replace that DI Container with a Pure DI option. That shouldn't be a problem, however. Just think of ASP.NET Core's Container as its configuration system. Consider the simplistic configuration system of ASP.NET (classic) MVC; its configuration system consisted just of a large dictionary. Although you were able to replace services in the dictionary, you couldn't remove the dictionary all together. It was just too embedded with the system. The same holds with ASP.NET Core's configuration system. The whole framework completely depends on its existence. And chances are slim that Boilerplate allows you to work without it.
But there's some good news...
Even though you can't remove the built-in configuration system, you can choose to apply Pure DI to your own application components and if you wish, you could even go back to the old school tightly coupled code base if you really want (which I can see from your examples you don't, fortunately).
How to do this with ASP.NET Boilerplate exactly I can't tell, unfortunately. But the freely available code samples of my book do demonstrate this concept using ASP.NET Core MVC here and especially here.
read many posts about the difference between the 3 idioms. But got more confused, then I ran into this article:
http://martinfowler.com/articles/injection.html
just want to see if I got this right. please correct me if I'm wrong.
Please notify me of correction and additions:
IoC- is the concept of decoupling an application from the implementation of a service it uses. The application contain a ref to Iservice and is not incharge of instanciating the concrete service.
There are at least two way to achive so:
DI - The concrete service is injected as a ctor param/throw a setter/throw interface injection (what does the latter mean?)
ServiceLocator - is a component that knows all the concrete services the application may need. The application explicitly asks for the concrete service from the Locator.
*IoC container is actualy a controls' factory ("provider").
I got a bit confused by the "when to prefer (1) or (2)" part in the article. could someone please tell from his own experience in a layman words ?
"Service Locator has a slight edge due to its more straightforward behavior. However if you are building classes to be used in multiple applications then Dependency Injection is a better choice."--> How is locator more straightforward ? because it uses method invocation explicitly ? What is it better to use DI when there are multiple applications?
IoC is the concept of decoupling an application from the implementation of a service it uses.
It is true that IoC goes hand in hand with decoupling interfaces from implementations, but I see it as a more general principle. This SO answer gives a very good explanation of the concept.
There are at least two way to achive so:
1) DI
2) ServiceLocator
I wouldn't say that the Service Locator pattern is an example of Inversion of Control. Quite the opposite - when you are using the Service Locator, you are acquiring the required dependencies in active way, nobody else does it for you (contrary to the DI, where the container handles the dependencies for you, you just have to give it a possibility of doing so - a setter, a constructor parameter or by implementing method of injection interface).
How is locator more straightforward ? because it uses method invocation explicitly?
I think that Martin Fowler is referring to the general idea of IoC that may make the code harder to understand if you've never seen the IoC/DI concept used before. On the other hand, the code using Service Locator to acquire some dependencies may be easier to grasp on first encounter.
What is it better to use DI when there are multiple applications?
When you are creating a component that is supposed to be reusable, the advantage of DI is that it doesn't make your component dependent on anything else than the original dependency (in MF's example, the MovieLister depends only on the MovieFinder interface when using DI).
Also, it is quite easy for others to use your component - the just have to pass the dependencies using the means of DI you provided.
When using the Service Locator, you also add dependency on the interface of the Service Locator itself. With segregated interface for the Locator, that may not be a problem. But it may also be harder for users of your component to satisfy the dependencies of your component, as MF writes:
The difference comes if the lister is a component that I'm providing to an application that other people are writing. In this case I don't know much about the APIs of the service locators that my customers are going to use. Each customer might have their own incompatible service locators.
I'm curious to know if it's possible to replace Spring.Net's built-in IoC container with Ninject. We use Ninject on my team for IoC in our other projects so I would like to continue using that container if possible.
Is this possible? Has anyone written a Ninject-Spring.Net Adapter??
Edit
I like many parts of the Spring.Net package (the data access, transactions, etc.) but I don't really like the dependency injection container. I would like to replace that with Ninject
Thanks
I can't talk specifically about converting Spring.NET to Ninject, but in general, all application code should be written to be DI Container-agnostic.
The best way to think about DI Containers is the Hollywood Principle. In DI terms, it becomes, don't call the DI Container, it'll call you.
In other words, the best application of DI is to use simple patterns such as Constructor Injection and Abstract Factory.
Most DI Containers worth their salt inherently understand these patterns, so no special, DI Container-specific, jumping through hoops should be needed.
This also means that ideally, you should only have DI Container-specific code in a single file in your application. This place is called the Composition Root, and this is where the DI Container wires up the entire object graph and gets out of the way.
If you follow this principle, you can easily exchange one DI Container for another.
The following posts have more details:
Where should I do Injection with Ninject 2+ (and how do I arrange my Modules?)
Design - Where should objects be registered when using Windsor
Jeffrey, can you please provide an example of what you are trying to do? I do not see your point, why/where/how you want to mix the 2 containers. If your code is entirely container-agnostic, then you won't have any problems to use either container for doing the wiring.
I meant everything I said in my other answer. However, I also realize that if you currently use Spring.NET as a Service Locator (i.e. you have code sprinkled all over your code base that queries the container), that answer may not be very helpful.
If this is the case, you may find the Common Service Locator project helpful. It is an open source project that attempts to abstract away specific Service Locators, hiding them all behind a common interface.
While they don't seem to have a Ninject implementation, they do have a Spring.NET implementation, so maybe that can take you halfway there.
For the record, I consider Service Locator an anti-pattern, and find that the Common Service Locator is the wrong answer to the wrong problem. In my eyes, it is utterly redundant, but it may be helpful to you as an intermediate step.
I have a solution with two relevant (to this question) projects, and a few others;
Class library with functionality used by several other projects.
ASP.NET MVC application.
My question is basically where I should do IoC with Ninject 2, considering...
The class library needs some DI love, among other things in the repository classes which need web request specific session objects (think Unit of Work).
The MVC app needs DI since with Ninject 2 you basically inherit from NinjectHttpApplication.
Unit tests for the class library need to be aware of this to inject a different set of repositories.
Unit tests for the web app need to be injected for the same reason.
I have painted myself into a mental corner here, because I only saw three options to begin with. DI in the class library, DI in the web app, or both, but there are problems with each:
I can't do DI only in the class library since the MVC app needs to inherit from NinjectHttpApplication to begin with.
I can't do DI only in the MVC app - the class library is used by other libraries, after all, and the MVC app shouldn't know too much about the internals of the library anyway.
I guess this is the only way out I can see: Independent IoC for both projects. The class library and the MVC app each have their own IoC setup and do DI for their stuff without really caring about each other.
Does anyone have some "best practices" or guidelines on how to do something like this? I can't imagine I'm the first person to end up in this situation, and it would sure be nice to know what the "proper" way to do this is...
Thanks!
I don't know NInject, but unless it works vastly different than Windsor, StructureMap etc. the answers tend to stay the same, as there are some common DI patterns. With that in mind:
The first thing to realize is that DI isn't tied to a particular framework such as NInject or Windsor. It is a set of techniques and design patterns to follow. You can do DI manually using so-called Poor Man's DI, but obviously it gets much better with a DI Container.
Why is this relevant? It is relevant because once you realize this, the corollary is that the vast majority of your application's code should have no knowledge of the DI Container whatsover.
So where do you use the DI Container? It should only be used in a Composition Root, which in your case would correspond to Global.asax. You can read a bit more about this in this SO answer - although that question is about Windsor, the principle remains the same.
How about your unit tests then? They should be completely ignorant of the DI Container as well. See this other SO answer for more details.
DI can be achieved in your library with copious use of Constructor Injection. You don't need to reference any DI Container to do that, but it makes life a lot easier if you use a DI Container to resolve all dependencies from the Composition Root.
What is an IoC container?
What is an IoC/DI framework?
Why do we need a framework for IoC/DI?
Is there any relationship between IoC/DI and AOP?
What is Spring.net/ninject with respect to IoC and AOP?
JMSA,
James Kovacs wrote a fantastic article which covers many of your questions I would recommend reading it Here
Spring.Net, Ninject, Unity, Castle Windsor, Autofac are all IOC containers which are configurable in different ways, many of them do also support AOP.
Frameworks for IOC/DI are useful because they provide standard mechanisms, for example if you are hiring a new developer it is much easier to say, we use this framework and pass them the links to the tutorials / help guide. At the same time these frameworks are tried and tested by a large community / companies.
Let me know if any of your questions remain unanswered after reading the article and the above answes and I'll do my best to provide further assistance.
From a semantics point of view...
Dependency Injection itself implies a dependency, i.e. something that is required for construction/use (the application's "core concerns"). For example, a car is not a car without an engine.
Aspects are described as being cross-cutting to the application's core concerns. That means both separate from and non-crucial to the core concerns (you could think of them as "nice-to-haves"). Since the application can run without aspects, are they really dependencies? For example, a car is still a car even without an immobiliser.
(Of course, this is from a theoretical standpoint. In the real world matters like security are often as crucial to the existence of a marketable product as the core concerns themselves.)
So in while in practice DI can be used to implement aspects, I would not call that process true DI. This is coming from someone who uses constructor injection exclusively.
Martin Fowler has a good article here on the meaning of Inversion of Control and Dependency Injection.
Spring.NET usage AOP is described in detail here. I'm more familiar with the Java-based version of Spring, so I cannot say with absolutely certainty that Spring.NET currently only supports proxy-based AOP.
That is, a class to be advised must implement an interface. Spring will create a dynamic proxy that implements this interface and delegates to the original target instance.
Although it does state:
In a future release we will implement proxies using inheritance, which will allow you to proxy classes without interfaces as well and will remove some of the remaining raw reference issues that cannot be solved using composition-based proxies.