Let's go

依赖注入框架

一、.内置DI

 案例1:

    public static class Sample01
    {
        public interface IAccount{
            public string getDataCZ();
        }
        public interface IMessage{ }
        public interface ITool{ }

        public class Account: IAccount{
            public string getDataCZ()
            {
                return "CHENZE 第一个依赖框架";
            }
        }
        public class Message: IMessage{}
        public class Tool: ITool{}

        public static void Run()
        {
            var provider = new ServiceCollection()
                .AddTransient<IAccount, Account>()
                .AddScoped<IMessage, Message>()
                .AddSingleton<ITool, Tool>()
                .BuildServiceProvider();


            IAccount entity = provider.GetService<IAccount>();
            Console.WriteLine(entity.getDataCZ());

            Debug.Assert(provider.GetService<IAccount>() is Account);
            Debug.Assert(provider.GetService<IMessage>() is Message);
            Debug.Assert(provider.GetService<ITool>() is Tool);
        }
    }
View Code

输出:

类 ServiceCollection (服务集合)的内置方法:(生命周期模式注册方法)

AddTransient:瞬时模式==一次性的

AddScoped:作用域模式==当前容器

AddSingleton:单例模式==根容器

构造函数注册点

1、容器能提供构造函数所需要的所有参数。

2、如果某一个构造函数的参数类型集合,能够成为所有合法构造函数参数类型集合的超集,那么这个构造函数就会被容器选择。

 服务范围

容器(通用表达)== 服务提供对象

 

二、Autofac (强大的注册功能)

 属性注入、程序集注入

在Startup类中增加

        public void ConfigureContainer(ContainerBuilder builder)
        {
            var assembly = Assembly.GetExecutingAssembly();
            // 程序集注册
            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
                // 筛选命名空间为 Services
                .Where(t => t.Namespace == assembly.GetName().Name + ".Services")
                // 暴露注册类型的接口
                .AsImplementedInterfaces()
                // 生命周期模式为Scope
                .InstancePerLifetimeScope();
        }

在program中增加.UseServiceProviderFactory(new AutofacServiceProviderFactory());

 

在控制器中,构造方法中进行赋值

    [Route("api/[controller]")]
    [ApiController]
    public class MessageController : ControllerBase
    {
        private readonly IMessage _message;

        public MessageController(IMessage message)
        {
            _message = message;
        }
        public IActionResult Get()
        {
            return Ok(_message.Text);
        }
    }

 三、Scrutor

不是依赖注入框架 .NET内置DI的扩展包,弥补.NET内置DI服务注册方式

在Startup类中增加

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.Scan(scan => scan
                .FromAssemblyOf<Startup>()
                .AddClasses(classes =>
                    classes.Where(t => t.Name.EndsWith("Service", StringComparison.OrdinalIgnoreCase)))
                .UsingRegistrationStrategy(RegistrationStrategy.Throw)//注册策略,重复的取最新的
                .AsMatchingInterface() //匹配接口名称
                .WithScopedLifetime()  //作用域
            );
        }

其他...

 

posted @ 2022-10-21 14:12  chenze  阅读(43)  评论(0编辑  收藏  举报
有事您Q我