zoukankan      html  css  js  c++  java
  • Autofac小例子

    AutoFac是.net平台下的IOC容器产品。今天学习一下它的使用方法。

    1.最简单的使用。

        public interface ITestDao
        {
            string SayHello();
        }
        public class TestDao : ITestDao
        {
            public string SayHello()
            {
                return "hello world!";
            }
        }
        
    
                var builder = new ContainerBuilder();
                builder.RegisterType<TestDao>().As<ITestDao>();
    
                IContainer container = builder.Build();
                var tdao = container.Resolve<ITestDao>();
                string saystr = tdao.SayHello();        
    builder.RegisterType<TestDao>().As<ITestDao>();注册TestDao是ITestDao的实现。
    然后下面进行调用就行。

    2.跟mvc一起使用
        public interface ITestDao
        {
            string SayHello();
        }
        public class TestDao : ITestDao
        {
            public string SayHello()
            {
                return "hello world!";
            }
        }
        
    
        public class HomeController : Controller
        {
    
            private ITestDao _testDao;
    
            public HomeController(ITestDao testDao) 
            {
                this._testDao = testDao;
            }
    
            public ActionResult Index()
            {
    
                string saystr = _testDao.SayHello();
    
                return View();
            }
    
        }

    在Global.asax里需要添加几行代码

      public class MvcApplication : System.Web.HttpApplication
        {
            protected void Application_Start()
            {
                //依赖注入
                var builder = new ContainerBuilder();
                SetupResolveRules(builder);
                builder.RegisterControllers(Assembly.GetExecutingAssembly());
                var container = builder.Build();
                DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    
    
                AreaRegistration.RegisterAllAreas();
    
                WebApiConfig.Register(GlobalConfiguration.Configuration);
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles);
            }
    
            private void SetupResolveRules(ContainerBuilder builder)
            {
                builder.RegisterType<TestDao>().As<ITestDao>();
            }
        }

    3.将注册代码放进配置文件。

        public interface ITestDao
        {
            string SayHello();
        }
        public class TestDao : ITestDao
        {
            public string SayHello()
            {
                return "hello world!";
            }
        }
        
    
        public class HomeController : Controller
        {
    
            private ITestDao _testDao;
    
            public HomeController(ITestDao testDao) 
            {
                this._testDao = testDao;
            }
    
            public ActionResult Index()
            {
    
                string saystr = _testDao.SayHello();
    
                return View();
            }
    
        }

    在Global.asax里需要添加几行代码

        protected void Application_Start()
            {
                //依赖注入
                var builder = new ContainerBuilder();
                builder.RegisterModule(new ConfigurationSettingsReader("autofac")); 
                builder.RegisterControllers(Assembly.GetExecutingAssembly());
                var container = builder.Build();
                DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    
    
                AreaRegistration.RegisterAllAreas();
    
                WebApiConfig.Register(GlobalConfiguration.Configuration);
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles);
            }

    在Web.config添加配置文件

    <configSections>
        <section name="autofac" type="Autofac.Configuration.SectionHandler, Autofac.Configuration" />
      </configSections>
    <autofac defaultAssembly="MvcApplication11">
        <components>
          <component type="MvcApplication11.Models.TestDao" service="MvcApplication11.Models.ITestDao" />
        </components>
      </autofac>

     4.系统自动注册,省略掉手工的配置和xml文件配置。(2014-07-16补充

    写一个基础接口,让你所有的接口都实现此接口,此接口起到的作用仅仅是个标识作用。

        public interface IAutofac//标识接口
        {
    
        }
        public interface ITestDao : IAutofac
        {
            string SayHello();
        }
        public class TestDao : ITestDao
        {
            public string SayHello()
            {
                return "hello world!";
            }
        }
        
        public class HomeController : Controller
        {
    
            private ITestDao _testDao;
    
            public HomeController(ITestDao testDao) 
            {
                this._testDao = testDao;
            }
    
            public ActionResult Index()
            {
    
                string saystr = _testDao.SayHello();
    
                return View();
            }
    
        }


    然后更改Global.asax里面的代码,AppDomain.CurrentDomain.GetAssemblies()获取当前程序域里所有的程序集,下面让RegisterAssemblyTypes自动注册所有继承了IAutofac的接口。

            protected void Application_Start()
            {
                //依赖注入
                var builder = new ContainerBuilder();
                //builder.RegisterModule(new ConfigurationSettingsReader("autofac"));
                
                var assemblys = AppDomain.CurrentDomain.GetAssemblies().ToList();
                builder.RegisterAssemblyTypes(assemblys.ToArray())
                    .Where(e => typeof(IAutofac).IsAssignableFrom(e) && e != typeof(IAutofac))
                    .AsImplementedInterfaces()
                    .InstancePerLifetimeScope();
    
                builder.RegisterControllers(Assembly.GetExecutingAssembly());
                
                var container = builder.Build();
                DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    
    
    
                AreaRegistration.RegisterAllAreas();
    
                WebApiConfig.Register(GlobalConfiguration.Configuration);
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles);
            }    
  • 相关阅读:
    vue2.5.2 在ie11打开空白的解决方法
    小程序自定义组件中observer函数的应用
    小程序将一个完整项目导入,报错ENOENT: no such file or directory(game.json)
    企业微信应用开发前准备
    jquery转盘抽奖游戏
    小程序路由跳转携带参数方法(直接跳转、事件委托跳转)
    小程序定义并使用模板template
    小程序真机预览,提示“音乐文件错误,播放失败”
    Java反编译
    DataX
  • 原文地址:https://www.cnblogs.com/ariklee/p/3843545.html
Copyright © 2011-2022 走看看