C# Ioc ASP.NET MVC Dependency Injection

2021-02-15 15:21

阅读:432

ASP.NET MVC Dependency Injection

同志们,非常快速的Ioc注册接口和注入Mvc Controller,步骤如下:

安装Unity.Mvc NuGet Package 在你的项目中,打开Package Manager Console进行安装。

技术分享图片

接下来我们可以看见两个类文件UnityConfig.cs 和 UnityMvcActivator.cs,接口注册需要在UnityConfig.cs里写你的接口实例,UnityMvcActivator.cs 它会帮助你自动resolver,放心吧,这个工具太无脑了,需要做的不多

1.注册接口

 public static class UnityConfig
    {
        #region Unity Container
        private static Lazy container =
          new Lazy(() =>
          {
              var container = new UnityContainer();
              RegisterTypes(container);
              return container;
          });

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

        /// 
        /// Registers the type mappings with the Unity container.
        /// 
        /// The unity container to configure.
        /// 
        /// 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.
        /// 
        public static void RegisterTypes(IUnityContainer container)
        {
            // NOTE: To load from web.config uncomment the line below.
            // Make sure to add a Unity.Configuration to the using statements.
            // container.LoadConfiguration();

            // TODO: Register your type‘s mappings here.
            // container.RegisterType();
            container.RegisterType();
        }

  2.注入接口到Controller

 public class HomeController : Controller
    {
        private IRepository _repository;
        public HomeController(IRepository repository)
        {
            _repository = repository;
        }

        public ActionResult Index()
        {
            var result = _repository.Test();
            return View(result);
        }

  3.启动Ioc初始化,代码在Global.asax

 public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            UnityConfig.RegisterTypes(new UnityContainer());
        }
    }

  少年F5启动你的程序,见证奇迹的时刻,最快速的搭建.net Mvc Ioc 接口实例以及Controller的依赖注入。

 

 

 

 


评论


亲,登录后才可以留言!