Dependency injection Unity:在运行时注册实例

Dependency injection Unity:在运行时注册实例,dependency-injection,unity-container,Dependency Injection,Unity Container,我好像弄不懂这个。我有一个依赖于服务的组件。该服务有一个只有在运行时才知道的URL。如何使用容器获取组件实例 public interface IService { Uri Url { get; set; } } public class Service : IService { public Uri Url { get; set; } } public class Component : IComponent { public Component(IService

我好像弄不懂这个。我有一个依赖于服务的组件。该服务有一个只有在运行时才知道的URL。如何使用容器获取组件实例

public interface IService
{
    Uri Url { get; set; }
}

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

public class Component : IComponent
{
    public Component(IService service) {... }
}
我只能考虑使用Unity作为服务定位器按需获取容器并注册我的运行时实例:

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

但我真的想避免SL。还有其他方法吗?

可能会重复标记,谢谢您的建议。我制作了一个
IServiceFactory
,它被注入到
组件的构造函数中,因此现在容器可以解析
IComponent
。但我需要以某种方式触发服务实例化,除了在
IComponent
上有一个方法外,我看不到其他方法,例如
SetServiceUrl(Uri Uri)
->,它在组件内部调用factory.Create(Uri)。这不是那个家伙想要避免的吗?