• Program 替换自带容器


    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}");
    }
    }

  • 相关阅读:
    cadence16.6 中orcad导出网表时ERROR (ORCAP-5004)
    (转)分享一个低功耗项目小小心得
    函数返回值传递
    STM32的SPI问题。
    关于MDK中:RO-data、RW-data、ZI-data
    一个技术汪的开源梦 —— 目录
    一个技术汪的开源梦 —— 微信开发工具包
    一个技术汪的开源梦 —— 公共组件缓存之分布式缓存 Redis 实现篇
    一个技术汪的开源梦 —— 基于 .Net Core 的组件 Nuget 包制作 & 发布
    Quartz.NET Windows 服务示例
  • 原文地址:https://www.cnblogs.com/Blog-JJ/p/11328098.html
Copyright © 2020-2023  润新知