ASP.NET核心:具有多个接口和单例生活方式的注册实现 [英] Asp.Net Core: register implementation with multiple interfaces and lifestyle Singleton

查看:40
本文介绍了ASP.NET核心:具有多个接口和单例生活方式的注册实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下接口和类定义:

public interface IInterface1 { }
public interface IInterface2 { }
public class MyClass : IInterface1, IInterface2 { }

有没有办法用这样的多个接口注册MyClass的一个实例:

...
services.AddSingleton<IInterface1, IInterface2, MyClass>();
...

并使用不同的接口解析MyClass的这个实例:

IInterface1 interface1 = app.ApplicationServices.GetService<IInterface1>();
IInterface2 interface2 = app.ApplicationServices.GetService<IInterface2>();

推荐答案

根据定义,服务集合是ServiceDescriptor的集合,它们是服务类型和实现类型对。

不过,您可以通过创建自己的提供程序函数来解决此问题,如下所示(感谢用户7224827):

services.AddSingleton<IInterface1>();
services.AddSingleton<IInterface2>(x => x.GetService<IInterface1>());

更多选项如下:

private static MyClass ClassInstance;

public void ConfigureServices(IServiceCollection services)
{
    ClassInstance = new MyClass();
    services.AddSingleton<IInterface1>(provider => ClassInstance);
    services.AddSingleton<IInterface2>(provider => ClassInstance);
}

另一种方式是:

public void ConfigureServices(IServiceCollection services)
{
    ClassInstance = new MyClass();
    services.AddSingleton<IInterface1>(ClassInstance);
    services.AddSingleton<IInterface2>(ClassInstance);
}

我们只提供相同的实例。

这篇关于ASP.NET核心:具有多个接口和单例生活方式的注册实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆