无需创建对象即可解析类型

chr*_*son 8 c# autofac

这是我的问题:我有一个容器,我将具体类型注册为接口.

builder.RegisterType<DeleteOrganization>().As<IDeleteOrganization>();
Run Code Online (Sandbox Code Playgroud)

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

Dan*_*elg 10

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


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));
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)