解决类型而不创建对象 [英] Resolve type without creating object

查看:36
本文介绍了解决类型而不创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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));
            }
        }
    }
}

这篇关于解决类型而不创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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