Nuget引用

Autofac
Autofac.Extensions.DependencyInjection


public IServiceProvider ConfigureServices(IServiceCollection services)
{
//使用autofac作为IOC
var containerBuilder = new ContainerBuilder();
containerBuilder.Populate(services);//将services里的内置的一些IOC和autofac整合
containerBuilder.RegisterModule< DefaultModuleRegister> ();
containerBuilder.RegisterType< BaseResponse> ().AsSelf();
return new AutofacServiceProvider(containerBuilder.Build());
}

新模块组件注册
containerBuilder.RegisterModule< DefaultModuleRegister> ();
using Autofac;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace YFJK.BasicServices.Host.Builder
{
public class DefaultModuleRegister : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType< Models.BaseResponse> ().AsSelf();

}
}
}

指定构造函数参数注册
containerBuilder.RegisterType< Neo4jHelper> ().WithParameters(new List< NamedParameter> ()
{
new NamedParameter("bolturl",Configuration["Neo4jSetting:Bolt"]),
new NamedParameter("httpurl",Configuration["Neo4jSetting:Url"]),
new NamedParameter("user",SecurityCommon.DecryptDES(Configuration["Neo4jSetting:User"])),
new NamedParameter("password",SecurityCommon.DecryptDES(Configuration["Neo4jSetting:Password"])),
}).SingleInstance();
其他注入实例调用注册
containerBuilder.Register(a => 
{
return new MongoClient(a.Resolve< YFConsulConfig> ().GetConfig("BertPreditMongoDBConfig:Conn"));
}).Named< MongoClient> ("BertPredit");

封装使用common

using Autofac;
using System;
using System.Collections.Generic;
using System.Text;

namespace YFJK.ScheduleTask.Library
{
public class AutoFacCommon
{
private static IContainer AutofacContainer;

public static void Init(IContainer container)
{
AutofacContainer = container;
}
public static void Dispose()
{
AutofacContainer.Dispose();
}

public static T GetInstance< T> (string name = null, ILifetimeScope scope = null)
{
if (scope == null)
{
using (scope = AutofacContainer.BeginLifetimeScope())
{
if (string.IsNullOrWhiteSpace(name))
{
return scope.Resolve< T> ();
}
return scope.ResolveNamed< T> (name);
}
}
else
{
if (string.IsNullOrWhiteSpace(name))
{
return scope.Resolve< T> ();
}
return scope.ResolveNamed< T> (name);
}
}
public static ILifetimeScope GetScope()
{
return AutofacContainer.BeginLifetimeScope();
}
}
}

注意 使用sqlconnection等资源时 按需求可能需要先获取scope 主动释放