TinyIoC:在单个实例上注册多个接口 [英] TinyIoC: Register multiple interfaces on a single instance

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

问题描述

Autofac允许使用.AsImplementedInterfaces()或链接的.As<>()调用与.SingleInstance()一起非常容易地将多个接口解析到同一实例. TinyIoC也可以做到吗?我只发现了如何注册同一接口的多个实现,但是没有办法链接注册等.

Autofac allows resolving multiple interfaces to the same instance very easily with .AsImplementedInterfaces() or chained .As<>() calls together with .SingleInstance(). Can this also be done with TinyIoC? I've only found how to register multiple implementations of the same interface, but there is no way of chaining registrations or the like.

据我了解,这对于IoC容器而言是非常重要的功能,不是吗?

From my understanding this is a quite important feature for an IoC container, isn't it?

推荐答案

如果我理解正确,那么你有类似的东西

If I'm understanding correctly you have something like

public class MyThing : IFoo, IBar
{
}

并且您希望以下内容彼此返回相同的实例:

And you want the following to return the same instance as each other:

Resolve<IFoo>();
Resolve<IBar>();

如果是这样,这是可能的,但是有点难看:

If so, it's possible, but it's a bit ugly:

container.Register<IFoo, MyThing>();
container.Register<IBar>((c,p) => c.Resolve<IFoo>() as IBar);

如果愿意,您可以将其包装为更好的语法,但是实际上,工厂委托实际上是在幕后发生的事情.

You could probably wrap that into some nicer syntax if you wanted to, but that factory delegate is effectively what will be happening under the hood.

这篇关于TinyIoC:在单个实例上注册多个接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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