zoukankan      html  css  js  c++  java
  • 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}");
    }
    }

  • 相关阅读:
    使用history.back()出现"警告: 网页已过期的解决办法"
    thinkphp5 如何将带分隔符的字符串转换成索引数组,并且遍历到前台
    MYSQL查询某字段中以逗号分隔的字符串的方法
    SpringBoot项目docker化
    全选Js
    【同步工具类】CountDownLatch
    Elasticsearch 2.3.2 安装部署
    从网络获取多张二维码图片,压缩打包下载
    传统的线程互斥技术:Synchronized关键字
    定时器的编写
  • 原文地址:https://www.cnblogs.com/Blog-JJ/p/11328098.html
Copyright © 2011-2022 走看看