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 @   chenze  阅读(45)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
有事您Q我
点击右上角即可分享
微信分享提示