I am new to IOC in general and I'm struggling a little to understand whether what I am trying to do makes any sense. I have a web forms application in which I want to create one module to define some bindings for me. The bindings will be used to inject repositories into my business manager classes, allowing me to unit test the business managers. Also I would like to use the container to inject the Entity Framework context into my repositories that way they all share the same context per http request. So here is what I am wondering:
I understand that I need to have the same kernel instance manage my object creation and their lifetime. For example if I want a one-per-httprequest type scenario I need the instance of the kernel to be available for that period of time. What if I need a singleton? Then it has to be application scoped somehow. So where exactly do I store the IKernel instance? It seems that I might want to make it a static in my Global.asax, is that the right approach and is thread safety a concern?
Since I am using Bind<> to define my bindings, how do I go about making that definition in the Web/UI layer when I shouldn't be referencing my data access layer from the UI? My references look like .Web --> .Business --> DataAccess. It seems like I want to tell the kernel "hey manage my data access instances, but don't have a reference to them at compile time." A binding such as this:
//Any object requesting an instance of AdventureWorksEntities will get an instance per request
Bind<AdventureWorksEntities>().ToSelf().InRequestScope();
I feel like I might be approaching this incorrectly, thank you.
Re part 1- have a look at the Ninject.Web extension - it keeps a Kernel at Application level. You can then manage other resources that have shorter lifetimes within that too.
Also, have a look around here for questions and examples on EF and L2S DataContext management wrt Ninject and DI in general (it's come up[ in the last few weeks)
UPDATE: This answer to another question from the same OP is far more concrete (There's a KernelContainer class with a .Inject( object) and a .Kernel)
It really depends on the complexity of your web app.
It sounds like you have a business and a data access layer; I would personally have an 'infrastructure' layer where I would store my DI repository and helper classes.
Related
I have been working on a MVC-EF application. We use DI container to inject dependencies into controllers, services, and repositories i.e across the UI-Services-DataAccess layers.
My question is regarding DI in services. One thing I have been confused about recently has been arisen from the need to use the behaviour (aka methods) that was implemented in one service in another service.
As far as I know, one service should not take dependency upon another because that would finally be leading closer to circular dependency and hence causing issues for DI container down the line.
So my question is, how should I work this out?
Should I be implementing the needed behaviour in second service (as part of its own methods) or I can somehow reuse it from the already implemented first service?
Can DI container help me in this regard?
Or is it that the way out is to outsource behaviour implemented in services into a separate Business Logic Layer, so it is available to each of the services? BTW, we currently do not have a separate BLL.
As far as I know, one service should not take dependency upon another because that would finally be leading closer to circular dependency and hence causing issues for DI container down the line.
This isn't quite true. In general, your objects refer to each other, forming a graph. When we discuss Dependency Injection, we normally call it a Dependency Graph.
As long as this graph is a Directed Acyclic Graph, all is good. The keyword here is acyclic, but it doesn't preclude reuse. You can have several services that use a single instance of another service; that just means that the service is shared.
Dependency Graphs can be as shallow or as deep as required, as long as they are acyclic, you can compose dependency graphs with confidence.
As usual the answer is, "It depends", however based on what you have said regarding needing some behavior/method to be available to multiple services, I think the last approach you mentioned makes the most sense.
Creating an independent class for "Support" functions can be useful in a lot of scenarios, particularly if you have methods that are a used for several services. DI should then be able to help you provide the "Support" class to its dependents.
I can see that similar questions has been asked previously, but being totally new to DI and .Net I am not able to grasps the entire solution or may not have found the right source....
I have assemblies WebAPI,BL,DL.
WebAPI is dependent on BL,
BL is dependent on DL,
WebAPI DOES NOT reference DL and I would like to keep it the same. There are few more assemblies but this is sufficient to illustrates the issues.
WebAPI has application start section therefore I can use it to initialize the Ninject Kernel and register dependencies for WebAPI project.
How could I achieve the same for BL and other assemblies?
There are a couple of different ways, you can use the Ninject Conventions to automagically resolve every ISomething to an implementation that has the same name (e.g. IThing -> Thing) or you can create a Ninject Module in each assembly which registers the dependencies (the module in your BL could load the module in your DL).
The approach you take would depend on whether you need to define different scopes for different objects, for example if you wanted some things resolved as singletons that may affect which method you use.
I think Mark Seemann's advice about this is great -- make a composition root at the highest possible layer of your application. For Web apps, this means in the Globals.asax file. I could expound on the good reason's for this, but the linked blog post does a better job.
This does break the layering you are trying to achieve, but only barely, and what I think is an appropriate way. If your web layer is appropriately thin (i.e., you could replace it with a thick client fairly easily) then it isn't a big loss. If you are really adverse to that, you could create a composition root in the BL for the DL.
During the life of my web application I know all of my services and repositories will be called. I would like to instantiate them once during the startup of the web application and refer to the instantiated references in my code.
Is there a common pattern for instantiating your services/repositories only once during the lifetime of a web application without making them static or singletons.
I would like to avoid making my services/repositories static classes or singletons for testability however instantiating them on every web request doesn't seem right when they are designed to be stateless and I know they will all be needed during the lifetime of the application.
I am using c#/asp.net.
The concept you need is called IoC / DI, and there are many frameworks for this. When you have a class like CustomerService and you need a CustomerRepository in it, by definition that is a dependancy, and you should pass it through the constructor of CustomerService - but then there is the question where you will instantiate CustomerService? Well, who uses that service should get it through constuctor too, it is maybe a CustomerPresenter, or some other class, irrelevant. My point is that with doing dependancy injections you structure your code to a very single point where an IoC / DI framework resolves those dependancies accoring to your rules.
At the very top of the program, you would have something like:
ICustomerPresenter presenter = IoC.Resolve<ICustomerPresenter>();
and everything will automatically come together behind the scenes.
To achieve this, here is an example with StructureMap:
For<ICustomerPresenter>().Use<CustomerPresenter>();
For<ICustomerService>().Singleton().Use<CustomerService();
For<ICustomerRepository>().Singleton().Use<CustomerRepository>();
With this, you keep the testability. I've simplified things a lot here, so this isn't much usable as-is, but there are plenty IoC / DI resources online, so check them out.
Note: for web applications you will want to check out handling lifecycle per request, you will rarely have singletons for entire web application.
Dependency Injection frameworks will take care of the lifetime of your objects.
Eg
container.RegisterType<MyService>().Singleton();
There are many DI frameworks choose what suits you best.
I would like to hear from you what are de the main advantages and drawbacks in applying dependency injection at the controller level, and/or domain level.
Let me explain; if I receive a IUserRepository as param for my User, I may proceed in two ways:
I inject IUserRepository direct on my domain object, then I consume User at controller level without newing objects, it means, I get them ready from the DI container.
I inject IUserRepository on my controller (say, Register.aspx.cs), and there I new all my domain objects using dependencies that came from the DI container.
Yesterday, when I was talking to my friend, he told me that if you get your domain objects from the container you loose its lifecicle control, as the container manages it for you, he meant that it could be error prone when dealing with large xml configuration files. Opinion which disagree as you may have a tests that loops through every domain object within an assembly and then asks the container whether thats a singleton, request scope, session scope or app escope. It fails if any of them are true. A way of ensuring that this kind of issue wont happen.
I fell more likely to use the domain approach (1), as I see a large saving on repetitive lines of code at controller level (of course there will be more lines at XML file).
Another point my friend rose was that, imagine that for any reason youre obligated to change from di container A to B, and say that B has no support for constructor injection (which is the case for a seam container, Java, which manipulates BC or only do its task via setter injection), well, his point is that, if I have all my code at controller level I'm able to refactor my code in a smoothly maner, as I get access to tools like Auto-Refactoring and Auto-Complete, which is unavailable when youre dealing with XML files.
Im stuck at this point, as I should have a decision to make right away.
Which approach should I leverage my architecture?
Are there other ways of thinking???
Do you guys really think this is a relevant concern, should I worry about it?
If you want to avoid an anemic domain model you have to abandon the classic n-tier, n-layer CRUDY application architecture. Greg Young explains why in this paper on DDDD. DI is not going to change that.
CQRS would be a better option, and DI fits very well into the small, autonomous components this type of architecture tends to produce.
I'm not into the Java sphere, but according to your details in your questions it seems like you use some kind of MVC framework (since you deal with Controllers and domain). But I do have an opinion about how to use DI in a Domain Driven architecture.
First there are several ways of doing DDD: Some uses MVC in presentation and no application service layer between MVC and Domain. Other uses MVP (or MVVM) and no service layer. BUT I think some people will agree on me that you very rarely inject repositories (or other services...). I would recommend to inject Repositories in Command (using MVC and no service layer), Presenter (if you use MVP) or Application Services (if you use service layer). I mostly use an application layer where each service get the repositories they need injected in constructor.
Second I wouldn't worry about switching between IoC containers. Most container framework today support ctor injection and can auto-resolve parameters. Now I know that you're a Java developer and I'm a MS developer, but MS Practices team has a Common Service locator that can helps you in producing code that are extremely non-dependent of which container framework you uses. There is probably some similar in the Java community.
So go for option 2. Hope I pushed you into right direction.
I'm a newbie to Dependency Injection. I have never used and never even undestood what it is exatcly all about, but after my last attack on this topic I found out that is a way of uncoupling an object and its dependencies, once they are not responsible for instantiating the concrete versions of its dependencies anymore, as now the container will do it for us and deliver the ready object in our hands.
Now the point is; "when should I use it?", ALWAYS??? Actually, as I'm a newbie and have never even seen a project that uses this pattern I can't undestand how I should apply it to my domain objects!!! It seems to me that I will nevermore instantiate my objects and the container will always do it for me, but then comes some doubts...
1) What about oobjects that part of its dependencies comes from the UI, for example;
public class User(String name, IValidator validator)
Say that I get the user name from the UI, so how will the conatiner know it and still delliver this object for me?
2) Theres other situation I'm facing; if a dependency is now an object that is already instantiated, say... a SINGLETON object, for example . I saw theres settings regarding out the scope of life of the dependency beign injected (im talking about Spring.NET, eg; http request scope)... BUT, request and other web related things are on my presentation layer, so how could I link both my presentation layer and my domain layer without breaking any design rule (as my domain should be totally unaware of where its is being consumed, not to have layer dependency, etc)
Im eager to hear from you all. Thanks very much.
In general, once you go IoC, you tend to want to register EVERYTHING with IoC and have the container spit out fully-hydrated objects. However, you bring up some valid points.
Perhaps a definition of "dependency" is in order; at its broadest, a dependency is simply a set of functionality (interface) that a given class requires a concrete implementation of in order for the class to work correctly. Thus, most non-trivial programs are full of dependencies. To promote ease of maintenance, loose coupling of all dependencies is generally preferred. However, even when loosely coupled, you don't need to automate instantiation of dependencies if those objects require specialized information that you don't want to pollute your IoC registry with. The goal is to loosely couple usage, not necessarily creation.
Concerning point 1, some IoC frameworks don't do well with being given external parameters. However, you can usually register a delegate as a factory method. That delegate may belong to an object like a Controller that is given external information by the UI. Logins are a perfect example: Create an object, say a LoginController, and register it with IoC as your ILoginController. You'll reference that controller on your Login page, it will be injected when the Login page is instantiated, and the login page will pass it the credentials entered. The Controller will then perform authentication, and will have a method GetAuthenticatedUser() that produces a User object. You can register this method with IoC as a Factory for Users, and whenever a User is needed, the factory delegate will either be evaluated, or passed wholesale to the dependent method which will call it when it really needs the User.
On point 2, setting up a single instance of an object is a strength of the IoC pattern. Instead of creating a true singleton, with a private instance constructor, static instance and static constructor to produce an instance, you simply register the class with IoC and tell it to only instantiate it once and use that one instance for all requests. The strength is the flexibility; if you later want there to be more than one instance, you just change the registration. You won't break any design pattern rules either way; the view will always have a Controller injected, whether that Controller is the same for all pages or a new instance per request.
1) this contructor is probably not the right one to use, may be you are injecting the validator in the wrong place/way.
2)Neighter View nor Model and nor Controller should be aware of there is an IoC, it should lie in the background architecture ( where MVC components are actually instantiated )
You should use IoC when you feel the architecture can became complex and has to be mantained by many people. If you are writing an enterprise application, or a UI you think to extend with plugins, you probably need it, if you are writing a command line utility, probably not.
You should use dependency injection whenever you want any of the following benefits:
The ability to replace modules easily
The ability to reuse modules between parts of the application, or different applications
When you want to do parallel development, so that components of a system can be developed in isolation and in parallel because they depend on abstractions
When you want easier maintenance of a system because of loose coupling
When you want testability (a specialisation of replacing modules). This is one of the biggest reasons for using DI
To answer your other questions:
1) You can configure many IoC containers so that certain constructor parameters can be specified, whilst others are resolved by the container. However, you may need to think about refactoring that piece of code, as a UserFactory may be more appropriate which takes the validator dependency, and has a NewUser method which takes a user name and returns a new user (either instantiating it directly or resolving from the container).
2) Each application you build will have a composition root, where your container is configured, and the root object is resolved. Each app will therefore have its own IoC configuration, so there is an expected link between the application type and the configuration settings. Any common abstraction registrations can be placed in configuration code which can be shared amongst all applications.