In the UI button click, I have to instantiate a DAL object before I can instantiate a BLL object. This seems cumbersome, to create the object dependencies before the object itself (more code than if the dependency was instantiated inside of BLL). Is this just the price you have to pay for using dependency injection?
It just bugs me that the preparation that is needed to instantiate BLL is in the UI. Is this the correct way to do dependency injection? Is there a way to separat开发者_如何学运维e the UI and BLL preparation logic cleanly?
class DAL{
//Data access layer
}
class BLL{
public BLL(DAL dal){
this.dal = dal;
}
private DAL dal;
}
buttonRun_Click(object sender, EventArgs e){
DAL dal = new DAL();
BLL bll = new BAL(dal);
bll.DoStuff();
}
If you need to create these BLL objects on-the-fly, I would use a factory object. The UI could have the factory injected into it, or if you're not using injection there, it could be instantiated in the constructor.
buttonRun_Click(object sender, EventArgs e){
BLL bll = balFactory.Create();
bll.DoStuff();
}
The factory object is then responsible for instantiating an instance of BLL, and knowing exactly how that is done.
But if you DON'T need a new one with each click, why not just inject a BLL instance into the UI itself?
Constructor chaining (poor man dependency injection)
public Bll() : this (new Dal()) { }
public Bll(IDal dal) // to provide other IDal implementations if needed
{
this.dal = dal;
}
Factory metods
private Bll() { }
public static Bll Create()
{
IBll bll = new Bll();
bll.Dal = new Dal();
return bll;
}
Dependancy injection using IoC tools (search the internet for this, frameworks for this are plentiful, either using configuration based XML injections, or in-language wirings ... - look for Castle Windsor, Spring.Net, Unity, StructureMap, Autofac, Ninject ...). Using some more advanced design patterns / application architecture is recommended (some MVC variation for example, so that you dont instantiate your objects in your presentation event handlers), although you are already starting to develop some good code by separating DALs, BLLs etc... Read: GoF Design Patterns, and general on application architectures
精彩评论