分类目录

链接

2016 年 9 月
 1234
567891011
12131415161718
19202122232425
2627282930  

近期文章

热门标签

新人福利,免费薅羊毛

现在位置:    首页 > .NET > 正文
Autofact IOC注入方式(二)
.NET 暂无评论 阅读(1,146)

然后, 修改Global.asax,

public class MvcApplication : System.Web.HttpApplication
{
        protected void Application_Start()
        {
            //Autofac初始化过程
            var builder = new ContainerBuilder();
            builder.RegisterControllers(typeof(MvcApplication).Assembly);//注册所有的Controller
            //开发环境下,使用Stub类
            builder.RegisterAssemblyTypes(typeof (MvcApplication).Assembly).Where(
                t => t.Name.EndsWith("Repository") && t.Name.StartsWith("Stub")).AsImplementedInterfaces();
            //发布环境下,使用真实的数据访问层
            //builder.RegisterAssemblyTypes(typeof(MvcApplication).Assembly).Where(
            //   t => t.Name.EndsWith("Repository")).AsImplementedInterfaces();

            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            //其它的初始化过程
            ........
        }
}

当我们使用下面这行代码的时候,所有的controller就都是使用Stub类的实例

//开发环境下,使用Stub类
builder.RegisterAssemblyTypes(typeof (MvcApplication).Assembly).Where(
             t => t.Name.EndsWith("Repository") && t.Name.StartsWith("Stub")).AsImplementedInterfaces();

当我们使用下面代码的时候,所有的controller就都用的是实际的数据访问类实例。

//发布环境下,使用真实的数据访问层
builder.RegisterAssemblyTypes(typeof(MvcApplication).Assembly).Where(t => t.Name.EndsWith("Repository")).AsImplementedInterfaces();

============ 欢迎各位老板打赏~ ===========

本文版权归Bruce's Blog所有,转载引用请完整注明以下信息:
本文作者:Bruce
本文地址:Autofact IOC注入方式(二) | Bruce's Blog

发表评论

留言无头像?