Unity:提供一个Func<>来实例化具体的接口实现

Unity: Provider a Func<> to instantiate a specific interface implementation

我们有一个带有 Unity 的 WPF 应用程序,我只有一个案例,我必须使用我们的一个库。该库为我们提供了一项服务,我们希望在我们的 ViewModel 中使用它,但是通过 "ServiceContainer" 自行创建它的方式。

我想在 Unity 中注册此服务,可以吗?

要做这样的事情?

ServiceContainer serviceContainer = new ServiceContainer(..., ..., ...);
unityContainer.RegisterType<IDialogService>(()=> serviceContainer.GetService<IDialogService>());

非常感谢

ServiceContainer serviceContainer = new ServiceContainer(..., ..., ...);

container.RegisterType<IDialogService>(
            new InjectionFactory(c => serviceContainer.GetService<IDialogService>()));

这是InjectionFactory看到这个msdn article

文章中的例子是:

container
  .RegisterType<ISurveyAnswerStore, SurveyAnswerStore>(
    new InjectionFactory((c, t, s) => new SurveyAnswerStore(
      container.Resolve<ITenantStore>(),
      container.Resolve<ISurveyAnswerContainerFactory>(),
      container.Resolve<IMessageQueue<SurveyAnswerStoredMessage>>(
        new ParameterOverride(
          "queueName", Constants.StandardAnswerQueueName)),
      container.Resolve<IMessageQueue<SurveyAnswerStoredMessage>>(
        new ParameterOverride(
          "queueName", Constants.PremiumAnswerQueueName)),
      container.Resolve<IBlobContainer<List<string>>>())));

您看到 new InjectionFactory((c, t, s) => ... 的 lambda 是容器,其中 c 是容器,因此您可以在创建类型时向容器询问其他类型。

为什么这有帮助

如果您想为 new ServiceContainer(..., ..., ...); 提供容器中的参数,那么:

container
    .RegisterType<IDialogService>(new InjectionFactory(c => 
    { 
        var arg1 = c.Resolve<IArg1>();
        var arg2 = c.Resolve<IArg2>();
        var arg3 = c.Resolve<IArg3>();

        ServiceContainer serviceContainer = new ServiceContainer(arg1, arg2, arg3);

        serviceContainer.GetService<IDialogService>()
    }));