AddSingleton(IServiceCollection, Type, Func<IServiceProvider,Object>)方法

这个方法是通过提供一个Func<IServiceProvider,Object>的delegate委托来实现服务的实例获取。具体怎么用,下面给一个简单例子:

using System;
using Microsoft.Extensions.DependencyInjection;

class Program
{

    interface ITianChao
    {
        void hello();
    }
    class TianChao:ITianChao
    {
        public int A{get;set;}
        public int B{get;set;}
        public TianChao(int a, int b)
        {
            A = a;
            B = b;
        }

        void ITianChao.hello()
        {
            System.Console.WriteLine("hello");
        }
    }

    class Hongse
    {
        public TianChao GetTC()
        {
            return new TianChao(44,55);
        }
    }

    static void Main(string[] args)
    {
        IServiceCollection services = new ServiceCollection();
        services.AddSingleton(typeof(TianChao), sp => {
            var hs = sp.GetService<Hongse>();
            return hs.GetTC();
        });
        services.AddSingleton(new Hongse());
        IServiceProvider serviceProvider = services.BuildServiceProvider();
        object mything = serviceProvider.GetService<TianChao>();
    }
}

当代码运行到最后一行serviceProvider.GetService()的时候,会去调用执行AddSinglenton()方法提供的delegate委托代码(也就是39-40行代码),委托代码传入的参数sp就是代码中创建的serviceProvider本身,执行完毕返回需要的服务对象。
因此AddSingleton(IServiceCollection, Type, Func<IServiceProvider,Object>)这个重载便于我们利用已经存在服务容器中的服务来生成需要取得的服务对象。
额外的文章:
依赖注入那些事儿

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐