向分层生命周期管理器注册ApplicationDbContext

时间:2018-11-22 23:59:59

标签: c# entity-framework asp.net-mvc-5 owin unity-container

我从现成的MVC5安装和Unity作为IoC容器开始。

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using System;
using System.Data.Entity;
using System.Web;
using DemoAPI.Repository;
using DemoMVC.Controllers;
using DemoMVC.Models;
using Unity;
using Unity.AspNet.Mvc;
using Unity.Injection;
using Unity.Lifetime;

namespace DemoMVC
{
    /// <summary>
    /// Specifies the Unity configuration for the main container.
    /// </summary>
    public static class UnityConfig
    {
        #region Unity Container
        private static Lazy<IUnityContainer> container =
          new Lazy<IUnityContainer>(() =>
          {
              var container = new UnityContainer();
              RegisterTypes(container);
              return container;
          });

        /// <summary>
        /// Configured Unity Container.
        /// </summary>
        public static IUnityContainer Container => container.Value;
        #endregion

        /// <summary>
        /// Registers the type mappings with the Unity container.
        /// </summary>
        /// <param name="container">The unity container to configure.</param>
        /// <remarks>
        /// There is no need to register concrete types such as controllers or
        /// API controllers (unless you want to change the defaults), as Unity
        /// allows resolving a concrete type even if it was not previously
        /// registered.
        /// </remarks>
        public static void RegisterTypes(IUnityContainer container)
        {

            container.RegisterType<IRepository, DemoRepository>();  

            #region OWIN
            container.RegisterType<AccountController>(new InjectionConstructor());
            container.RegisterType<DbContext, ApplicationDbContext>(new HierarchicalLifetimeManager());
            container.RegisterType<IUserStore<ApplicationUser>,
                UserStore<ApplicationUser>>(new PerRequestLifetimeManager());
            container.RegisterType<ApplicationUserManager>(new PerRequestLifetimeManager());
            container.RegisterType<IAuthenticationManager>(
                new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));
            container.RegisterType<ApplicationSignInManager>(new PerRequestLifetimeManager());
            #endregion



        }
    }
}

我在这里主要担心的是:向分层生命周期管理器注册ApplicationDbContext。手动注册DbContext并在注册其余类型时使用此实例-似乎很难为所有请求使用相同的永恒db上下文。但是,每个请求对我来说意义不大,因为每个请求实例化dbContext似乎浪费了很多资源。

还有其他/更好的方法可能会丢失我吗?我尝试查找文档来查找统一性,尤其是终身经理,但是我发现的所有内容似乎都已经过时了。

0 个答案:

没有答案