Resolve type without creating object

前端 未结 2 705
攒了一身酷
攒了一身酷 2021-02-08 17:41

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

builder.RegisterType().As

        
2条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-08 18:11

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

提交回复
热议问题