1. nuget添加 Autofac
2.Autofac.Extensions.DependencyInjection
3.Autofac.Extras.IocManager.DynamicProxy
1.替换自带容器
.UseServiceProviderFactory(new AutofacServiceProviderFactory());
2.在Startup.cs内容添加
public void ConfigureContainer(ContainerBuilder containerBuilder)
{
containerBuilder.RegisterModule<CustomAutofacModule>();
}
3. CustomAutofacModule内容
public class CustomAutofacModule : Autofac.Module
{
protected override void Load(ContainerBuilder containerBuilder)
{
var assembly = this.GetType().GetTypeInfo().Assembly;
var builder = new ContainerBuilder();
var manager = new ApplicationPartManager();
manager.ApplicationParts.Add(new AssemblyPart(assembly));
manager.FeatureProviders.Add(new ControllerFeatureProvider());
var feature = new ControllerFeature();
manager.PopulateFeature(feature);
builder.RegisterType<ApplicationPartManager>().AsSelf().SingleInstance();
builder.RegisterTypes(feature.Controllers.Select(ti => ti.AsType()).ToArray()).PropertiesAutowired();
containerBuilder.Register(c => new CustomAutofacAop());//aop注册
containerBuilder.RegisterType<TestServiceA>().As<ITestServiceA>().SingleInstance().PropertiesAutowired();
containerBuilder.RegisterType<TestServiceC>().As<ITestServiceC>();
containerBuilder.RegisterType<TestServiceB>().As<ITestServiceB>();
containerBuilder.RegisterType<TestServiceD>().As<ITestServiceD>();
containerBuilder.RegisterType<JDDbContext>().As<DbContext>();
containerBuilder.RegisterType<UserService>().As<IUserService>();
containerBuilder.RegisterType<A>().As<IA>().EnableInterfaceInterceptors();
}
}
4.AOP实现
/// <summary>
/// 自定义的Autofac的AOP扩展
/// </summary>
public class CustomAutofacAop : IInterceptor
{
public void Intercept(IInvocation invocation)
{
Console.WriteLine($"invocation.Methond={invocation.Method}");
Console.WriteLine($"invocation.Arguments={string.Join(",", invocation.Arguments)}");
invocation.Proceed(); //继续执行
Console.WriteLine($"方法{invocation.Method}执行完成了");
}
}
public interface IA
{
void Show(int id, string name);
}
[Intercept(typeof(CustomAutofacAop))]
public class A : IA
{
public void Show(int id, string name)
{
Console.WriteLine($"This is {id} _ {name}");
}
}