将同一类型注册到多个接口 [英] Register the same type to multiple interfaces

查看:38
本文介绍了将同一类型注册到多个接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以将一种类型注册到多个接口吗?

It is possible to register one type to multiple interfaces?

我有实现两个接口的类

MyService : IService1, IServier2 {}

我想为两个接口注册这个类型.

I would like to register this type for both interfaces.

container.RegisterType<IService1, MyService>(CreateLifetime());
container.RegisterType<IService2, MyService>(CreateLifetime());

不幸的是,在解决之后我有两个不同的实例.我尝试使用公共生命周期,但后来收到消息说我不能.

Unfortunately during after resolving I have two different instances. I tried use common lifetime but then I got message that I can't.

推荐答案

我通常这样写:

      .RegisterType<MyService>(CreateLifeTime())
      .RegisterType<IService1, MyService>()
      .RegisterType<IService2, MyService>();

当然,使用 TransientLifetimeManager,您仍将获得两个不同的 MyService 实例.

Of course with a TransientLifetimeManager, you still will get two different instances of MyService.

以上代码适用于 PerResolveLifetimeManagerPerResolveLifetimeManagerPerThreadLifetimeManager.

The code above works with PerResolveLifetimeManager, PerResolveLifetimeManager, PerThreadLifetimeManager.

这篇关于将同一类型注册到多个接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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