解决类型而不创建对象

问题描述:

这是我的问题:我有一个容器,用于在其中注册具体类型作为接口.

Here's my problem: I have a container where I register concrete types as interfaces.

builder.RegisterType<DeleteOrganization>().As<IDeleteOrganization>();

我正在为正在执行的序列化项目实现SerializationBinder,而我需要实现的BindToType方法要我返回Type对象. BindToType方法为我提供了assemblyNametypeName(两个字符串)来帮助我创建类型对象.我想做的是如果typeName是一个接口,我想问一下Autofac该接口Type的具体实现Type是什么,而没有实际创建对象.有可能吗?

I'm implementing a SerializationBinder for a serialization project I'm doing and the BindToType method that I need to implement wants me to return a Type object. The BindToType method gives me an assemblyName and typeName (both strings) to help me create a type object. What I want to do is if the typeName is an interface, I want to ask Autofac what the concrete implementation Type is for that interface Type without actually having it create the object. Is that possible?

如果您使用RegisterType注册服务,则可以这样做.我写了一个快速测试,应该可以帮助您提取所需的数据.

If you are using the RegisterType to register your services this is possible. I wrote a quick test that should help you extract the data you need.


private interface IDeleteOrganization
{

}

private class DeleteOrganization : IDeleteOrganization
{

}


[TestMethod]
public void CanResolveConcreteType()
{
    var builder = new ContainerBuilder();

    builder.RegisterType()
        .As();

    using(var container = builder.Build())
    {
        var registration = container.ComponentRegistry
            .RegistrationsFor(new TypedService(typeof (IDeleteOrganization)))
            .SingleOrDefault();

        if (registration != null)
        {
            var activator = registration.Activator as ReflectionActivator;
            if (activator != null)
            {
                //we can get the type
                var type = activator.LimitType;
                Assert.AreEqual(type, typeof (DeleteOrganization));
            }
        }
    }
}