开发者

Unity: register instance at runtime

开发者 https://www.devze.com 2023-04-09 16:54 出处:网络
I can\'t seem to figure out this one. I have a component which depends on a service. The service has a URL which is only known at runtime. How can I get a Component instance using the container?

I can't seem to figure out this one. I have a component which depends on a service. The service has a URL which is only known at runtime. How can I get a Component instance using the container?

开发者_运维技巧
public interface IService
{
    Uri Url { get; set; }
}

public class Service : IService
{
    public Uri Url { get; set; }
}

public class Component : IComponent
{
    public Component(IService service) {... }
}

I can only think of using Unity as Service Locator to get the container on demand and register my runtime instance:

var service = new Service { Url = new Uri("http://...") };
Container.Resolve<IUnityContainer>().RegisterInstance<IService>(service);
var component = Container.Resolve<IComponent>();

But I really want to avoid SL. Is there another way?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号