Asp.Net Core默认注入方式下多接口实现如何注入以及如何指定构造函数注入

12 篇文章 2 订阅

多接口实现注入

一般情况下,我们只需要注入定义的接口以及相应的实现,最多也就是某个接口会有多个实现,也就是多态,但因为C#是允许实现多接口,也就是某个类实现了多个接口定义,那这种情况下,又该如何注入呢?
假设我们分别有接口IMutiInterface01IMutiInterface02,每个接口都各自包含获取一个Id值的方法,以及他们的实现类MultiInterfaceImplt,该类的两个实现均返回同一个Guid,为了方便直观,这里没有把两个接口的方法设定为相同的名称,感兴趣的同学也可以将两个接口约定改为相同的方法名称(比如都改为GetIdAsync),然后通过接口的显式声明来调用不同的接口实现(比如IMutiInterface01.GetIdAsync)。

    public interface IMutiInterface01
    {
        ValueTask<string> GetId01Async();
    }

    public interface IMutiInterface02
    {
        ValueTask<string> GetId02Async();
    }

    public class MultiInterfaceImplt : IMutiInterface01, IMutiInterface02
    {
        private string _id = Guid.NewGuid().ToString();

        public ValueTask<string> GetId01Async()
        {
            return new ValueTask<string>(this._id);
        }

        public ValueTask<string> GetId02Async()
        {
            return new ValueTask<string>(this._id);
        }
    }

一般情况下,我们是按如下方式注入的

            services.TryAddScoped<IMutiInterface01, MultiInterfaceImplt>();
            services.TryAddScoped<IMutiInterface02, MultiInterfaceImplt>();

然后是用于测试的API

    [Route("[controller]")]
    public class OrderController : ControllerBase
    {
        private readonly IMutiInterface01 mutiInterface01;
        private readonly IMutiInterface02 mutiInterface02;

        public OrderController(
            IMutiInterface01 mutiInterface01,
            IMutiInterface02 mutiInterface02)
        {
            this.mutiInterface01 = mutiInterface01;
            this.mutiInterface02 = mutiInterface02;
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<string> Get(CancellationToken cancellationToken)
        {
            var content = $@"Interface01的Id为 { await mutiInterface01.GetId01Async() } 
Interface02的Id为 { await mutiInterface02.GetId02Async() }";
            return content;
        }
    }
}

这时候通过postman进行调用测试,会发现返回的id值是两个不同的guid,因为默认.Net Core认为这应该是两个不同的实现注入
在这里插入图片描述

虽然程序没报错,但对于我们来说,这两个方法返回的id应该是相同的,毕竟注册时,我们注册的生命周期是Scoped,所以我们对于注册的过程需要调整下

            services.TryAddScoped<IMutiInterface01, MultiInterfaceImplt>();
            //services.TryAddScoped<IMutiInterface02, MultiInterfaceImplt>();
            services.TryAddScoped<IMutiInterface02>(p =>
            {
                var tmp = (MultiInterfaceImplt)p.GetService<IMutiInterface01>();
                return tmp;
            });

这样写的方式,其实是通过强行转换来解决注入的不是同一个对象实例问题,或者我们也可以通过下面注入指定实现,但其实与第一种方式本质没啥区别

            services.TryAddScoped<MultiInterfaceImplt>();
            services.TryAddScoped<IMutiInterface01>(p => p.GetService<MultiInterfaceImplt>());
            services.TryAddScoped<IMutiInterface02>(p => p.GetService<MultiInterfaceImplt>());

这时候我们再调用下接口,会发现这时候返回的id都是相同的,满足了我们的需求
在这里插入图片描述

使用指定构造函数注入

一般情况下,我们在每个类里面,都只会包含一个构造函数,然后这个构造函数包含了所有需要注入的接口或其它参数,但凡事都有例外,也许你的需求就需要支持有多个构造函数,依赖注入时,需要使用指定的构造函数,其它情况下,需要使用其它的构造函数,在.Net Core里面,当有多个构造函数时,必须有一个构造函数包含了其它构造函数的所有构造参数,否则程序会在注入时产生异常
继续利用上面的IMutiInterface01IMutiInterface02,假设我们有下面这种例子情况,包含所有构造参数的构造函数当前是被注释的

    public class DifferentCtorParameters
    {
        private readonly IMutiInterface01? mutiInterface01;
        private readonly IMutiInterface02? mutiInterface02;
        
        public DifferentCtorParameters(IMutiInterface02 mutiInterface02)
        {
            this.mutiInterface02 = mutiInterface02;
        }

        //public DifferentCtorParameters(IMutiInterface01 mutiInterface01, IMutiInterface02 mutiInterface02)
        //{
        //    this.mutiInterface01 = mutiInterface01;
        //    this.mutiInterface02 = mutiInterface02;
        //}

        public DifferentCtorParameters(IMutiInterface01 mutiInterface01)
        {
            this.mutiInterface01 = mutiInterface01;
        }


        public ValueTask<int> Complete()
        {
            var ret = 0;
            if (mutiInterface01 != null)
            {
                ret |= 1;
            }
            if (mutiInterface02 != null)
            {
                ret |= 2;
            }
            return new ValueTask<int>(ret);
        }
        
    }

注册时按正常的Scoped进行注册

services.TryAddScoped<DifferentCtorParameters>();

此时运行程序,会产生异常
在这里插入图片描述
这种情况下,我们可以通过ActivatorUtilitiesConstructorAttribute以及ActivatorUtilities来解决注入问题,我们将注入代码进行如下调整

services.TryAddScoped(p => ActivatorUtilities.CreateInstance<DifferentCtorParameters>(p));

此时运行程序的话,程序就不会产生异常,我们在Controller添加测试代码

        [HttpGet("ctor")]
        [AllowAnonymous]
        public async Task<int> GetCtor(CancellationToken cancellationToken)
        {
            var ret = await this.ctorParameters.Complete();
            return ret;
        }

通过调用API,会发现返回的值是2,也就是说第一个构造函数被拿来初始化了
在这里插入图片描述
我们在第二个构造函数上添加ActivatorUtilitiesConstructorAttribute注释

        [ActivatorUtilitiesConstructor]
        public DifferentCtorParameters(IMutiInterface01 mutiInterface01)
        {
            this.mutiInterface01 = mutiInterface01;
        }

这时候再调用API,可以发现返回值变成了1,也就是说这时候用的是IMutiInterface01对应的构造函数。

没写ActivatorUtilitiesConstructor以及写了一个ActivatorUtilitiesConstructor的情况下,程序是正确运行的,我们再试下每个构造函数上都加上了ActivatorUtilitiesConstructor注释,此时再运行程序时,程序还是可以正常启用运行,但当我们调用API时,会产生异常,提示[ActivatorUtilitiesConstructor]注释只能有一个
在这里插入图片描述
好吧,这整篇博客其实都是没多大意义的内容,毕竟这篇博客里面的内容使用场景太小众,既然都这样了,再补充个没多大意义的东西,在.Net Core 2.2之前,想要用第三方依赖注入来替换默认的依赖注入,我们需要将StartupConfigureServices方法返回值从void改为IServiceProvider,而在3.0以及之后的版本,是在ProgramCreateHostBuilder方法中增加UseServiceProviderFactory调用来进行替换,是不是奇怪的知识又增加了……

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值