(1):首先新建web项目,建立好相关类库架构。
(2):在程序包管理器中添加autofac程序及引用。
(3):然后在Startup.cs类中的ConfigureServices添加如下代码。
public IServiceProvider ConfigureServices(IServiceCollection services)
{
//Aotufac注入方式开始
var builder = new ContainerBuilder();
services.AddMvc();
//Aotufac注入方式开始
builder.RegisterType(typeof(DBSession)).As(typeof(IDBSession));
var Repository = Assembly.Load("Repository");
builder.RegisterAssemblyTypes(Repository).Where(t => t.Name.EndsWith("Repository")).AsImplementedInterfaces().InstancePerLifetimeScope();
//注册领域服务
builder.RegisterAssemblyTypes(Assembly.Load("Domain")).Where(u => u.Namespace == "Domain.Service" || u.Namespace == "Domain.Interface");
//注册应用程序
builder.RegisterAssemblyTypes(Assembly.Load("APP")).Where(u => u.Namespace == "APP" || u.Name.EndsWith("APP"));
builder.Populate(services);
this.ApplicationContainer = builder.Build();
return new AutofacServiceProvider(this.ApplicationContainer);//Aotufac注入方式结束
}
(4):在Home控制器中依赖注入相应访问类:
private CommentAPP _commentAPP;
public HomeController(CommentAPP commentAPP)
{
_commentAPP = commentAPP;
}