C# MVC IOC、依赖注入

在MVC5中依赖注入,本文介绍通过扫描类型RegisterAssemblyTypes来进行注册

另外还有扫描模块RegisterAssemblyModules来注册

 使用Autofac框架进行组件的依赖注入

Autofac是.NET领域最为流行的IOC框架之一,传说是速度最快的一个

先通过Nuget安装程序包

PM> install-package atuofac

PM> install-package atuofac.mvc5

一般的做法是设计一个空的IDependency的接口,让所有想要加入到IOC中的类实现这个接口

    interface IDependency
    {
    }
    public class NormalService:IDependency
    {
        public string testIoc()
        {
            return "IoC Test";
        }
    }

在Global中进行设置

添加引用

using Autofac;
using Autofac.Integration.Mvc;//注册Controller时需要

            //获取已加载到此应用程序域的执行上下文中的程序集。
            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies().ToArray();
// Assembly[] assemblies = Directory.GetFiles(AppDomain.CurrentDomain.RelativeSearchPath, "*.dll").Select(Assembly.LoadFrom).ToArray(); //var assemblies = Assembly.GetExecutingAssembly(); //创建autofac管理注册类的容器实例 ContainerBuilder builder = new ContainerBuilder(); //注册所有实现了 IDependency 接口的类型 Type baseType = typeof(IDependency); builder.RegisterAssemblyTypes(assemblies) .Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract) .AsSelf().AsImplementedInterfaces() .PropertiesAutowired() .InstancePerLifetimeScope(); // 设置MVC的DependencyResolver注册点 builder.RegisterControllers(assemblies) .AsSelf() .PropertiesAutowired() .InstancePerLifetimeScope(); DependencyResolver.SetResolver(new AutofacDependencyResolver(builder.Build()));

NormalService的使用

        public NormalService normalService { get; set; }

        [HttpGet]
        public JsonResult GetIocMethod()
        {
            string strIocReturn= normalService.testIoc();
            return Json(strIocReturn,JsonRequestBehavior.AllowGet);
        }

如果NormalService是实现接口INormalService的话

    public interface INormalService
    {
         string testIoc();
    }
    public class NormalService:IDependency,INormalService
    {
        public string testIoc()
        {
            return "IoC Test";
        }
    }
        public INormalService normalService { get; set; }

        [HttpGet]
        public JsonResult GetIocMethod()
        {
            string strIocReturn= normalService.testIoc();
            return Json(strIocReturn,JsonRequestBehavior.AllowGet);
        }

除了通过统一实现IDependency的方式来进行注册外,单个类型的注册

            builder.RegisterType<NormalService>().As<INormalService>()
                .AsSelf()
                .PropertiesAutowired()
                .InstancePerLifetimeScope();

builder.RegisterType<DbContextScopeFactory>().As<IDbContextScopeFactory>()
.AsSelf().AsImplementedInterfaces()
.InstancePerLifetimeScope().PropertiesAutowired();

 

这些就是在MVC中进行依赖注入的方式

猜你喜欢

转载自www.cnblogs.com/pashanhu/p/9656840.html