Autofac依赖注入框架

最近使用Autofac框架做项目的依赖注入,感觉挺好用的。

没有深入研究,只是拿来用用,具体可以去官网看看:https://autofac.org/。

这里只是贴一下最近项目的配置:

public partial class Startup
    {
        public void ConfigureContainer(IAppBuilder app)
        {
            var builder = new ContainerBuilder();

            // You can register controllers all at once using assembly scanning...
            builder.RegisterControllers(typeof(MvcApplication).Assembly);

            // Get your HttpConfiguration.
            var config = GlobalConfiguration.Configuration;

            // Register your Web API controllers.
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            // OPTIONAL: Register the Autofac filter provider.
            builder.RegisterWebApiFilterProvider(config);

            // OPTIONAL: Register the Autofac model binder provider.
            builder.RegisterWebApiModelBinderProvider();

            // ...or you can register individual controlllers manually.
            //builder.RegisterType<HomeController>().InstancePerRequest();

            builder.RegisterModule<AutofacWebTypesModule>();//Register Web Abstractions

            builder.RegisterSource(new ViewRegistrationSource());//Enable Property Injection for View Pages

            builder.RegisterFilterProvider();//Enable Property Injection for Action Filters

            builder.RegisterType<EFDbContext>().As<IDbContext>().InstancePerRequest();
            builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope();
            builder.RegisterType<MemoryCacheManager>().As<ICacheManager>().InstancePerRequest();
            #region  Service
            builder.RegisterType<SysUserService>().As<ISysUserService>().InstancePerLifetimeScope();
            //注册各种服务
            
            #endregion
            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            RuntimeContext.Instance.ContainerManager = new ContainerManager(container);//存储到全局实例中
            // OWIN MVC SETUP:

            // Register the Autofac middleware FIRST, then the Autofac MVC middleware.
            app.UseAutofacMiddleware(container);
            app.UseAutofacMvc();
        }
    }

项目是基于MVC的,利用Startup的partialt特性,加了上面依赖注入配置方法ConfigureContainer,然后可以在MVC的Startup类的Configuration方法中调用该方法,如下:

 public void Configuration(IAppBuilder app)
 {
   ConfigureContainer(app);
 }

OK,依赖注入搞定了.

posted @ 2017-09-18 10:11  我没有领悟  阅读(252)  评论(0编辑  收藏  举报