您的位置:首页 > 编程语言 > ASP

Asp.Net Core 2.0 之旅---AutoFac IOC容器的使用教程

2017-12-27 17:12 726 查看
其实早就想开 Core 2.0的文章了,奈何基础薄弱。只能猥琐发育。。。哈哈

Core 2.0 作为开源跨平台框架。现在它的热度是比较高的。也是微软老大重点项目。

接下来我会一步步的演示Asp.Net Core 2.0 项目如何引用AutoFac 容器,并如何使用它!

1、在你建立的web 项目中 右键 选中 管理Nuget 程序管理包,搜索Autofac.Configuration,Autofac.Extensions.DependencyInjection 并安装最新版。



2、在 StarpUp 中 配置 Autofac,注意的是 要将 ConfigureServices 的返回类型 从 void 类型 改成 IServiceProvider ,

并 return new AutofacServiceProvider(ApplicationContainer); 官方解释是,让第三方容器接管Core 的默认DI。

public class Startup
{
public IConfiguration Configuration { get;}
public Startup(IHostingEnvironment env)
{
Configuration = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json").Build();
}
public IContainer ApplicationContainer { get; private set; }
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc();
var builder = new ContainerBuilder();//实例化 AutoFac  容器
builder.Populate(services);
ApplicationContainer = builder.Build();
return new AutofacServiceProvider(ApplicationContainer);//第三方IOC接管 core内置DI容器
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{

app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}

app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}


3、至此,AutoFac 就配置成功了。这里我 给几个示例 如何去注册 

1:

builder.RegisterType(typeof(IShareYunSourseAppService)).As(typeof(ShareYunSourseAppService));//ShareYunSourseAppService 实现了IShareYunSourseAppService


2:  

var assemblys = Assembly.Load("ShareYunSourse.Application");//获取ShareYunSourse.Application 程序集,ShareYunSourse.Application 是类库名
var baseType = typeof(IDependency);//IDependency 是一个接口
builder.RegisterAssemblyTypes(assemblys)
.Where(m => baseType.IsAssignableFrom(m) && m != baseType)
.AsImplementedInterfaces().InstancePerLifetimeScope();
这几句代码的意思是,只要接口继承了IDependency ,就注册继承该接口的接口。AsImplementedInterfaces  表示注册的类型,以接口的方式注册 ,InstancePerLifetimeScope即为每一个依赖或调用创建一个单一的共享的实例

4、使用方法,我推荐的构造方法注入的方式

public class ShareYunSourseAppService :IShareYunSourseAppService
{
private readonly IRepository<YunSourse> _yunsourseIRepository;
public ShareYunSourseAppService(IRepository<YunSourse> yunsourseIRepository)
{
_yunsourseIRepository = yunsourseIRepository;
}
public async Task GetName()
{
var list = _yunsourseIRepository.GetAll().Where(m=>!string.IsNullOrEmpty(m.Content)).ToList();

}
}


5、也许有朋友要问这个IRepository<YunSourse> _yunsourseIRepository 是如何依赖注入的。关于这块就涉及到仓储的概念的。我会在下一盘文章中详细解释,并用代码展示仓储泛型 是如何依赖注入的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐