• .NETCore 内置DI扩展 Scrutor


    Scrutor 不是依赖注入框架,而是.NET内置DI的扩展包。弥补了.NET内置DI的不足。其底层还是内置DI,性能比第三方DI框架Autofac更高效。但是没有Autofac强大。如果只是为了用程序集注册,而用不到autofac的强大功能,建议用scrutor。

    第一步:Nuget添加Scrutor

    第二步:编码

    接口、服务类 Service

    namespace WebApplication_scrutor
    {
        public interface IMessageService
        {
            public string Text { get; set; }
        }
        public class MessageService : IMessageService
        {
            public string Text { get; set; }
            public MessageService()
            {
                Text = "Hello Message1111";
            }
        }
    }
    

    startup 类ConfigureServices 方法

    public void ConfigureServices(IServiceCollection services)
            {
                //注册webapi服务
                services.AddControllers();
                //scrutor的方式
                services.Scan(selector => selector
                    //加载startup 类所在的程序集
                    .FromAssemblyOf<Startup>()
                    //过滤程序集中需要注册的类
                    .AddClasses(classes => classes.Where(t => t.Name.EndsWith("Service")))
    
                    //暴露匹配的接口
                    .AsMatchingInterface()
                    //.AsImplementedInterfaces() //暴露的是每一个接口
                    //.As(t => t.GetInterfaces()) //暴露所有接口
                    //.AsSelf() //暴露自己,因为是单一类型,没有接口
    
                    //设置生命周期
                    .WithScopedLifetime()
                    ) ;
            }
    

    Controller

    [Route("api/[controller]")]
        [ApiController]
        public class MessageController : ControllerBase
        {
            private readonly IMessageService messageService;
            public MessageController(IMessageService _messageService)
            {
                messageService = _messageService;
            }
    
            public IActionResult Get() => Ok(messageService.Text);
    
        }
    
  • 相关阅读:
    将文件写进数据库的方法
    立个Flag
    JQuery_学习1
    js制作一个简单的选项卡
    输出数据库中的表格的内容(pdo连接)
    不饮鸡汤的寂寞先生
    详细谈Session
    详细谈Cookie
    php字符串操作函数练习2
    ios开发网络学习五:MiMEType ,多线程下载文件思路,文件的压缩和解压缩
  • 原文地址:https://www.cnblogs.com/Fengyinyong/p/14248485.html
Copyright © 2020-2023  润新知