Autofac在MVC中实现自动注册

1、在控制台执行命令安装Autofac组件

Install-Package Autofac

Install-Package Autofac.Mvc5 -Version 4.0.2

using Autofac.Integration.Mvc; //注册控制器时会用到

2、定义IAutoInject、ISendMessage接口及其实现类

 public interface IAutoInject { }
 public interface ISendMessage : IAutoInject { string SendMessage(); }
 public class Phone : ISendMessage { }
 public class Email : ISendMessage { }

3、添加Autofac配置项并初始化

a、在App_Start文件夹中添加AutofacConfig.cs,并在其中添加初始化方法

b、在Global.asax文件下的Application_Start()内调用AutofacConfig.Initialize();进行注册

public static void Initialize()
{
    var builder = new ContainerBuilder();
    //获取IAutoInject的Type
    var iautoInject = typeof(IAutoInject);
    //获取ISendMessage的Type
    var isendMessage = typeof(ISendMessage);
    //获取所有程序集
    var assemblies = System.Web.Compilation.BuildManager.GetReferencedAssemblies().Cast().ToArray();
    //获取某程序集
    //Assembly[] assemblies = new Assembly[] 
    //{                 
    //    Assembly.Load("AutofacDemo.Web"),
    //    Assembly.Load("AutofacDemo.Models")
    //};
    //自动注册接口
    builder.RegisterAssemblyTypes(assemblies)
           .Where(b => b.GetInterfaces().Any(c => c == iautoInject && b != iautoInject))
           .AsImplementedInterfaces().InstancePerLifetimeScope();
    builder.RegisterAssemblyTypes(assemblies)
           .Where(b => b.GetInterfaces().Any(c => c == isendMessage && b != isendMessage))
           .AsImplementedInterfaces().InstancePerLifetimeScope();
    //自动注册控制器
    builder.RegisterControllers(assemblies);
    var container = builder.Build();
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}

4、编写测试代码

public interface IAutoInject{  }
public interface ISendMessage : IAutoInject
{
    string SendMessage();
}
public class Phone : ISendMessage
{
    public string SendMessage()
    {
        return "Phone";
    }
}
public class Email : ISendMessage
{
    public string SendMessage()
    {
        return "Email";
    }
}
public class HomeController : Controller
{
    private ISendMessage sendMessage;

    public HomeController()
    {
    }    

    public HomeController(ISendMessage sendMessage)
    {
        this.sendMessage = sendMessage;
    }

    public ActionResult Index()
    {
        string result = sendMessage.SendMessage();
        return View();
    }
}

sendMessage.SendMessage()可以正确返回结果说明依赖注入成功。

你可能感兴趣的:(Autofac)