(精华)2020年8月19日 ASP.NET MVC 控制器工厂实现Unity容器注入

DI工厂

public class DIFactory
{
     
    private static IUnityContainer _Container = null;
    private readonly static object DIFactoryLock = new object();
    public static IUnityContainer GetContainer()
    {
     
        if (_Container == null)
        {
     
            lock (DIFactoryLock)
            {
     
                if (_Container == null)
                {
     
                    //container.RegisterType
                    ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
                    fileMap.ExeConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "CfgFiles\\Unity.Config");
                    Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
                    UnityConfigurationSection section = (UnityConfigurationSection)configuration.GetSection(UnityConfigurationSection.SectionName);
                    _Container = new UnityContainer();
                    section.Configure(_Container, "ruanmouContainer");
                }
            }
        }
        return _Container;
    }
}

Unity配置文件

<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Unity.Configuration"/>
  </configSections>
  <unity>
    <sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Unity.Interception.Configuration"/>
    <containers>
      <!--<container name="Advanced">
        <extension type="Interception"/>
        <register type="System.Data.Entity.DbContext, EntityFramework" mapTo="Advanced.EF6.Models.TencentClassRoomContext,Advanced.EF6.Models"/>

        <register type="Advanced.Bussiness.Interface.IUserService,Advanced.Bussiness.Interface" mapTo="Advanced.Bussiness.Service.UserService, Advanced.Bussiness.Service">
          <interceptor type="InterfaceInterceptor"/>
          <interceptionBehavior type="Advanced.AspNetMVC.AOP.LogBeforeBehavior, Advanced.AspNetMVC"/>
          <interceptionBehavior type="Advanced.AspNetMVC.AOP.LogAfterBehavior, Advanced.AspNetMVC"/>
        </register> 
      </container>-->

      <container name="AdvancedContainer">
        <extension type="Interception"/>
        <register type="Advanced.Bussiness.Interface.IUserService,Advanced.Bussiness.Interface" mapTo="Advanced.Bussiness.Service.UserService, Advanced.Bussiness.Service">
          <interceptor type="InterfaceInterceptor"/>
          <interceptionBehavior type="Advanced.AspNetMVC.Utility.AOP.LogBeforeBehavior, Advanced.AspNetMVC"/>
          <interceptionBehavior type="Advanced.AspNetMVC.Utility.AOP.LogAfterBehavior, Advanced.AspNetMVC"/>
        </register> 
        <register type="System.Data.Entity.DbContext, EntityFramework" mapTo="Advanced.EF6.Models.TencentClassRoomContext, Advanced.EF6.Models"/>
        <register type="Advanced.Bussiness.Interface.ICompanyService,Advanced.Bussiness.Interface" mapTo="Advanced.Bussiness.Service.CompanyService, Advanced.Bussiness.Service"/>
        <!--<register type="Advanced.Bussiness.Interface.IUserService,Advanced.Bussiness.Interface" mapTo="Advanced.Bussiness.Service.UserService, Advanced.Bussiness.Service"/>-->
      </container>
    </containers>
  </unity>
</configuration>

AOP相关

public class LogAfterBehavior : IInterceptionBehavior
{
     
    public IEnumerable<Type> GetRequiredInterfaces()
    {
     
        return Type.EmptyTypes;
    }

    public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
    {
     
        IMethodReturn methodReturn = getNext()(input, getNext); 
        Console.WriteLine("这里是方法执行后。。。");
        return methodReturn;
    }

    public bool WillExecute
    {
     
        get {
      return true; }
    }
}
/// 
/// 不需要特性
/// 
public class LogBeforeBehavior : IInterceptionBehavior
{
     
    public IEnumerable<Type> GetRequiredInterfaces()
    {
     
        return Type.EmptyTypes;
    }
    public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
    {
     
        //Session 
        ///这里是方法执行前
        Console.WriteLine("这里是方法执行前");
        return getNext().Invoke(input, getNext);
    }

    public bool WillExecute
    {
     
        get {
      return true; }
    }
}
public class XTControllerFactory : DefaultControllerFactory
{
     
    private Logger logger = new Logger(typeof(XTControllerFactory));

    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
     
        this.logger.Warn($"{controllerType.Name}被构造...");

        IUnityContainer container = DIFactory.GetContainer();
        //return base.GetControllerInstance(requestContext, controllerType);
        return (IController)container.Resolve(controllerType);
    }
}

全局注册

protected void Application_Start()
{
     

    AreaRegistration.RegisterAllAreas();//注册区域
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);//注册全局的Filter
    RouteConfig.RegisterRoutes(RouteTable.Routes);//注册路由
    BundleConfig.RegisterBundles(BundleTable.Bundles);//合并压缩 ,打包工具 Combres

    ControllerBuilder.Current.SetControllerFactory(new XTControllerFactory());

    this.logger.Info("网站启动了。。。");
}

使用

public class ThirdController : Controller
{
     
    private IUserService _iUserService = null;
    private ICompanyService _iCompanyService = null;
    private IUserCompanyService _iUserCompanyService = null;
    /// 
    /// 构造函数注入---控制器得是由容器来实例化
    /// 
    /// 
    /// 
    /// 
    public ThirdController(IUserService userService, ICompanyService companyService, IUserCompanyService userCompanyService)
    {
     
        this._iUserService = userService;
        this._iCompanyService = companyService;
        this._iUserCompanyService = userCompanyService;

        
    }


    // GET: Third
    public ActionResult Index()
    {
     
        //JDDbContext context = new JDDbContext();
        //IUserService service = new UserService(context);
        IUserService service = this._iUserService;
        User user = service.Find<User>(2);
        return View();
    }
}

你可能感兴趣的:(#,ASP.NET,MVC)