autofactory 属性注入

  之前不懂net core  在网上搜索了一堆autofac 的属性注入,都特么错的,至少现在net 5 新版的 用不了。

 今天闲空,自己整理一下了 ,代码没有分层架构,都混成UI 层。总体预览如下图

  

1 是我封装的静态方法  写入的都是autof 注册关系

2.1 aotofac 属性选择器, 2.2 标记属性  哪个属性需要ioc 的

3 接口类型

4 实现接口类

二 使用方法 

  1 nuget 包  autofac  和Autofac.Extensions.DependencyInjection  2个包

 2  Program类 代码如下 替换ioc 容器

   

  public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
            .UseServiceProviderFactory(new AutofacServiceProviderFactory()) ;
    }

3自定义静态方法  如下 

静态方法如下  :

    public static class AutoSatic
    {

        public static void  RegsterType(this ContainerBuilder builder)
        {
            builder.RegisterType<test>().As<Itest>();
    
            builder.RegisterType<World>().As<IWorld>().PropertiesAutowired(new CustomPropertySelector());
        }
    }

 属性注入是默认支持构造函数注入的。放心大胆的用

 注意的是 属性是放在 实现类标记的!!!!!!!!!!

World实现类 ,

具体代码如下
    public class World : IWorld
    {

        public World()
        {
            Console.WriteLine($"{nameof(World)}被构造了!!!!");
        }

        /// <summary>
        /// 标记属性注入
        /// </summary>
        [CustomPropery]
        public Itest _itest { get; set; }

        public void Worlds()
        {
            Console.WriteLine($"{nameof(World)} World !!!!");
        }


        public void aa()
        {
            _itest.hello();
        }
    }

4 特性类CustomProperyAttribute 只是标记 啥也不是

    [AttributeUsage(AttributeTargets.Property)]
    public class CustomProperyAttribute:Attribute
    {
    }

CustomPropertySelector 类 

    /// <summary>
    /// autofac  找出所有属性上是否摸个特性
    /// </summary>
    public class CustomPropertySelector : IPropertySelector
    {
        public bool InjectProperty(PropertyInfo propertyInfo, object instance)
        {  //需要一个判断
            //;如果标记的有CustomPropertyAttribute特性返回True:返回true;就构造实例
            return propertyInfo.CustomAttributes.Any(iterator => iterator.AttributeType == typeof(CustomProperyAttribute));
        }
    }

 最后调用一下   

属性 有值了。棒棒哒!!!!!!  

原文地址:https://www.cnblogs.com/jasontarry/p/15324364.html