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(object), sp => {
var hs = sp.GetService<Hongse>();
return hs.GetTC();
});
services.AddSingleton(new Hongse());
IServiceProvider serviceProvider = services.BuildServiceProvider();
object mything = serviceProvider.GetService<object>();
}
}
當代碼運行到最後一行的時候,會去調用執行AddSinglenton()方法提供的delegate委託代碼(也就是39-40行代碼),委託代碼傳入的參數sp就是代碼中創建的serviceProvider本身,執行完畢返回需要的服務對象。
因此AddSingleton(IServiceCollection, Type, Func<IServiceProvider,Object>)這個重載便於我們利用已經存在服務容器中的服務來生成需要取得的服務對象。