Mvc Autofac构造器注入

新建MVC项目,添加程序集引用

定义接口ILog

 public interface ILog
    {
        string  Save(string message);
    }

类TxtLog实现接口ILog

public class TxtLog:ILog
    {
        public string  Save(string message)
        {
            return "TxtLog";  
        }
    }

类DbLog实现接口ILog

  public class DbLog:ILog
    {
        public string Save(string message)
        {
            return "DbLog";
        }
    }

修改HomeController里面Index方法,改为如下,注意引用

     private ILog _log;

        //构造器注入
        public HomeController(ILog log)
        {
            _log = log;
        }
        
        // GET: /Home/

        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";
            ViewBag.LogTypeName = _log.Save("");
            return View();
        }

修改页面Index.cshtml ,添加如下代码

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        <h2>ILog's type name is @ViewBag.LogTypeName</h2>      
    </div>
</body>
</html>

修改Global.asax,在Application_Start()方法里面添加如下代码,注意引用Autofac、Autofac.Integration.Mvc以及别的引用

 protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            //依赖注入 
            ContainerBuilder builder = new ContainerBuilder();
            builder.RegisterType<TxtLog>().As<ILog>().InstancePerHttpRequest();
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsImplementedInterfaces();
            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }

 注意: DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); 这个必须放在builder.RegisterControllers(Assembly.GetExecutingAssembly());的后面,不然会出现错误:没有为该对象定义无参数的构造函数。

运行结果

posted @ 2016-03-02 16:12  成败在我手  阅读(1202)  评论(1编辑  收藏  举报