EF6 (code first), MVC, Unity, and a service layer without a repository

前端 未结 4 1802
没有蜡笔的小新
没有蜡笔的小新 2021-02-09 00:11

My application is using SQL Server 2012, EF6, MVC and Web API.

It\'s also using a repository and assorted files such as:

DatabaseFactory.cs
Disposable.c         


        
4条回答
  •  花落未央
    2021-02-09 00:23

    Setting up Unity for ASP.NET MVC and WebAPI is quite easy if you install and add the Unity.Mvc* and Unity.WebAPI* Nuget packages to your project. (The * is a version number, like 3 or 4 or 5. Look for the appropriate versions for your project. Here are for example the links to the Unity.Mvc 5 package and to the Untity.WebAPI 5 package.)

    The usage of these packages is explained in this blog post.

    The building blocks are roughly like so:

    You build a unity container and register all your dependencies there, especially the EF context:

    private static IUnityContainer BuildContainer()
    {
        var container = new UnityContainer();
    
        container.RegisterType(new HierarchicalLifetimeManager());
    
        container.RegisterType();
        container.RegisterType();
        container.RegisterType();
        // etc., etc.
    
        return container;
    }
    

    MyContext is your derived DbContext class. Registering the context with the HierarchicalLifetimeManager is very important because it will ensure that a new context per web request will be instantiated and disposed by the container at the end of each request.

    If you don't have interfaces for your services but just concrete classes you can remove the lines above that register the interfaces. If a service needs to be injected into a controller Unity will just create an instance of your concrete service class.

    Once you have built the container you can register it as dependency resolver for MVC and WebAPI in Application_Start in global.asax:

    protected void Application_Start()
    {
        var container = ...BuildContainer();
    
        // MVC
        DependencyResolver.SetResolver(
            new Unity.MvcX.UnityDependencyResolver(container));
    
        // WebAPI
        GlobalConfiguration.Configuration.DependencyResolver =
            new Unity.WebApiX.UnityDependencyResolver(container);
    }
    

    Once the DependencyResolvers are set the framework is able to instantiate controllers that take parameters in their constructor if the parameters can be resolved with the registered types. For example, you can create a CustomerController now that gets a CustomerService and an EmailMessenger injected:

    public class CustomerController : Controller
    {
        private readonly ICustomerService _customerService;
        private readonly IEmailMessenger _emailMessenger;
    
        public CustomerController(
            ICustomerService customerService,
            IEmailMessenger emailMessenger)
        {
            _customerService = customerService;
            _emailMessenger = emailMessenger;
        }
    
        // now you can interact with _customerService and _emailMessenger
        // in your controller actions
    }
    

    The same applies to derived ApiControllers for WebAPI.

    The services can take a dependency on the context instance to interact with Entity Framework, like so:

    public class CustomerService // : ICustomerService
    {
        private readonly MyContext _myContext;
    
        public CustomerService(MyContext myContext)
        {
            _myContext = myContext;
        }
    
        // now you can interact with _myContext in your service methods
    }
    

    When the MVC/WebAPI framework instantiates a controller it will inject the registered service instances and resolve their own dependencies as well, i.e. inject the registered context into the service constructor. All services you will inject into the controllers will receive the same context instance during a single request.

    With this setup you usually don't need a context = new MyContext() nor a context.Dispose() as the IOC container will manage the context lifetime.

提交回复
热议问题