TinyIoC: Register multiple interfaces on a single

2020-08-26 03:51发布

问题:

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.

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

回答1:

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.