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核心:具有多个接口和单例生活方式的注册实现


基础教程推荐
猜你喜欢
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01