Dependency injection with unity in a class library project

笑着哭i 提交于 2021-02-18 17:35:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!