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

  • 相关阅读:
    香港的困境
    美国的制度
    媒体行业
    张首晟生前最著名演讲:这几句话可以总结人类所有知识
    印度的发展
    中国互联网发展解读
    cnblogs博客使用LaTeX公式
    Stanford CS229 Machine Learning by Andrew Ng
    强化学习在业界的实际应用
    AUC计算方法
  • 原文地址:https://www.cnblogs.com/Blog-JJ/p/11328098.html
Copyright © 2011-2022 走看看