I'm a little bit confused around Constructor Injection pattern and rule Don’t call the container; it’ll call you.
Can somebody explain me (and maybe someone else) how real application should derive all DI advantage using Constructor Injection ? I give for that some simple and i think common example:
DomainObject
RepositoryObject
DaoObject
The relations is obvious (I think) - RepositoryObject need DaoObject,DomainObject need Repository.
Using Constructor Injection I assume that I can forget (in most cases) about NEW keyword, but when, where and how should I create new objects (mainly domain)? I must write factories for all classes? Should I refer to DI Container in that factory?
The best will be when somebody show me some real app example (please not Asp.Net MVC :) ) or sketch some project structure.
I don't get your class relationship so here's a more obvious ;-) example:
class FooService
{
IFooRepository FooRepository { get; set; }
public Service(IFooRepository fooRepository)
{
this.FooRepository = fooRepository;
}
}
class Controller
{
IFooService FooService { get; set; }
IBarService BarService { get; set; }
public Controller(IFooService fooService, IBarService barService)
{
this.FooService = fooService;
this.BarService = barService;
}
}
As you've already said - there is no new FooRepository()
nor new FooService()
code anywhere.
The answers and Mark Seemann's link is enough but i want to add something. As a beginner to DI ( which i am) this question is always bugs me: "Ok there is no new but when and how my real objects are called and injected?". It took me for a while for me to understand and apply.
As you follow the answers and links you will see that. You should register your interfaces and classes in your applications Global.asax file for web application. For instance if you are using Ninject go to nuget and download Ninject.Web ( which is for webforms) and apply it like in this example http://azolotar.blog.com/2010/06/22/ninject-2-0-in-webforms/
Keypoint in the example.
I should add this, BasePage implementation is pretty easy ( here is the code on github) you probably already have an basepage so adding this line KernelContainer.Inject(this); to your base page's OnInit can solve the problem. One last remainder, if you are going to use anything in ascx you should override your ascx's OnInit so container can solve dependencies.
I know you said no MVC or web :)But the logic is the same
Damn this sounds not helpful answer but anyway , hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With