.net mvc 项目如何使用Munq IOC

Munq 是一款轻型IOC框架,据说速度是最快的,可以看这个介绍:Introduction to Munq IOC Container for ASP.NET

那么如何使用它呢?

首先项目引用,用Nuget 包管理,搜索Munq 找到了,引用即可。

使用Munq 很简单,只需要四步:

1、创建容器

using Munq;

namespace ApiTest.Ioc
{
    public class Container
    {
        private static readonly object _mutex = new object();
        private static IocContainer _instance;

        public static IocContainer Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_mutex)
                    {
                        if (_instance == null)
                        {
                            _instance = new IocContainer();
                        }
                    }
                }

                return _instance;
            }
        }
    }
}

 

2、新建一个ControllerFactory类,继承自DefaultControllerFactory,这样就可以在controller中使用构造函数注入

using Munq;
using System;
using System.Web.Mvc;
using System.Web.Routing;

namespace ApiTest.Ioc
{
    public class MunqControllerFactory : DefaultControllerFactory
    {
        private readonly IocContainer _container;

        public MunqControllerFactory()
        {
            _container = Container.Instance;
        }

        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            if (null == controllerType)
            {
                return null;
            }

            return _container.Resolve(controllerType) as IController;
        }
    }
}

 

3、注册接口&设置Controller factory

public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            Container.Instance.Register<IHttpClientHelper, HttpClientHelper>();
            Container.Instance.Register<ITest, Test>();

            var controllerFactory = new MunqControllerFactory();
            ControllerBuilder.Current.SetControllerFactory(controllerFactory);
        }
    }

 

4、通过构造函数注入

 public class HomeController : Controller
    {
        private ITest _test;
        public HomeController(ITest test)
        {
            _test = test;
        }
        public ActionResult Index()
        {
            ViewBag.Title = "Home Page";
            var dd = _test.Show();

            return View();
        }
    }

Test类和ITest接口不再展示。

posted @ 2021-07-19 15:42  SilverFox8588  阅读(67)  评论(0编辑  收藏  举报