问题
I am new with the dependency injection pattern. I'm a little confused about few things.
Scenario:
I have a class library project called 'MailCore'. This project has interfaces and classes that perform all email sending stuff. I have an MVC project called 'The site'. It uses the 'MailCore' project to send email. I have Unity in this project and the UnityContainer is registered and things are working fine.
I also have another class library library project called 'SiteRepo'. Sometimes, to perform some specific tasks, I have to send email from this project. Therefore the 'MailCore' project is referenced in this project, too.
Problem:
I have installed Unity from NuGet in the 'SiteRepo' project and it doesn't seem to create any UnityConfig in this class library project. How would I register a UnityContainer here?
Code:
TheSite:
Public class JobController : Controller
{
private readonly IEmailBuilder mailBuilder;
public JobController(IEmailBuilder mailBuilder)
{
this.mailBuilder = mailBuilder;
}
public ActionResult Create(....)
{
JobRepo j = new JobRepo();
j.Create(....);
}
}
UnityConfig (this is in the web app 'The Site'):
public static class UnityConfig
{
public static void RegisterComponents()
{
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
container.RegisterType<IEmailBuilder, EmailBuilder>();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
}
SiteRepo:
Public class JobRepo()
{
Public bool Create(...)
{
//some other code to create a job....
//have to send email using MailCore !! The problem area in concern..
}
}
回答1:
If you must use a DI Container like Unity (instead of Pure DI), you should install it into your Composition Root, which is 'The site'.
From there, you can reference the library projects and configure your container.
来源:https://stackoverflow.com/questions/30877168/dependency-injection-with-unity-in-a-class-library-project