Asp.Net Core: register implementation with multiple interfaces and lifestyle Singleton(ASP.NET核心:具有多个接口和单例生活方式的注册实现)
本文介绍了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核心:具有多个接口和单例生活方式的注册实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:ASP.NET核心:具有多个接口和单例生活方式的注册实现
基础教程推荐
猜你喜欢
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
