.NET MVC5专题(控制器工厂实现Unity【IOC】容器注入)

第三方容器unity工厂

public class DIFactory
{
    public static IUnityContainer GetContainer()
    {
        IUnityContainer 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;
    }
}

替换mvc控制器工厂

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;
    /// <summary>
    /// 构造函数注入---控制器得是由容器来实例化
    /// </summary>
    /// <param name="userService"></param>
    /// <param name="companyService"></param>
    /// <param name="userCompanyService"></param>
    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();
    }
}

具体的unity配置请参照https://blog.csdn.net/weixin_41181778/article/details/103439805

发布了146 篇原创文章 · 获赞 120 · 访问量 4735

猜你喜欢

转载自blog.csdn.net/weixin_41181778/article/details/103947482