Including a dependency with unity in a class library project

I am new to dependency injection pattern. I am a little confused about a few things.

Scenario:

I have a class library project called "MailCore". This project has interfaces and classes that handle all email. I have an MVC project called Site. It uses the MailCore project to send email. I have Unity in this project and the UnityContainer is registered and everything is working fine.

I also have another class library project called "SiteRepo". Sometimes, in order to accomplish some specific tasks, I have to send an email from this project. Therefore, the project "MailCore" is also mentioned in this project.

Problem:

I installed Unity from NuGet in a SiteRepo project and did not seem to create a UnityConfig in that class library project. How can I register the 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 Site web application):

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..
   }
}

      

+3


source to share


1 answer


If you must use a DI container like Unity (instead of Pure DI ), you must set it to your Composition Root , which is the "site".



From there, you can link to library projects and customize your container.

+5


source







All Articles