• 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());的后面,不然会出现错误:没有为该对象定义无参数的构造函数。

    运行结果

  • 相关阅读:
    CSUSTOJ-伊井野弥子是风纪委员(简单BFS)
    CSUSTOJ-石上优不想留级(一维坐标三分及思维解法)
    CSUSTOJ-哈希的纸团(mid思维)
    CSUSTOJ-辉夜大小姐想被猜中(简单暴力)
    CSUSTOJ-藤原书记想要探病(简单矩阵快速幂)
    CSUSTOJ-石上优想要逃离(STL+思维暴力)
    CSUSTOJ-白银御行想展示(思维题)
    CSUSTOJ-藤原书记的佩斯(简单数学)
    CSUSTOJ-白银探病篇(简单思维)
    Odoo发邮件被服务器退回
  • 原文地址:https://www.cnblogs.com/bubugao/p/AutofacDemo.html
Copyright © 2020-2023  润新知