标题可能具有误导性,但基本上我想DryIoc.Container
解析一个接口的特定实现,其类型(实现接口的类的类型)在运行时给出(注册了同一接口的多个实现)。我不能用来识别实现,因为解析实现的代码预计会执行以下操作:获取我们想要的实现(实现的类型是通过我们在运行时读取的配置获取的)。serviceKey
container.Resolve<IService>(*** here specify the runtime type of the implementation ***)
using System;
using DryIoc;
namespace DryIoc_example
{
interface IService { }
class ServiceImpl_1 : IService { }
class ServiceImpl_2 : IService { }
class Program
{
static void Main(string[] args)
{
var container = new Container();
// register my implementations of IService
// this could be done at runtime using
// container.Register(typeof(IService), typeof(ServiceImpl_1));
container.Register<IService, ServiceImpl_1>();
container.Register<IService, ServiceImpl_2>();
// now, i want the container to resolve a specific
// implementation of IService ( ServiceImpl_2 in this case)
// this line doesn't work and throws
var myService = container.Resolve<IService>(typeof(ServiceImpl_2));
// this line is expected to print the type of ServiceImpl_2
Console.WriteLine(myService.GetType());
}
}
}
`
上面的代码抛出:
Unable to resolve DryIoc_example.IService {RequiredServiceType=DryIoc_example.ServiceImpl_2}
Where CurrentScope: null
and ResolutionScope: null
and Found registrations:
DefaultKey.Of(0),{ID=20, ImplType=DryIoc_example.ServiceImpl_1}}
DefaultKey.Of(1),{ID=21, ImplType=DryIoc_example.ServiceImpl_2}}
我知道我可以获得接口的所有注册实现并过滤具有我想要的实现的接口(使用DryIoc 的维护者类似于此响应https://stackoverflow.com/a/37069854/5767019的代码),但是当我要求它时,我想不出一种方法让容器解决它!