首页 > 解决方案 > Prism 7 DI中的Register vs RegisterInstance vs RegisterSingleton

问题描述

我正在尝试在 Prism 7 中为 DI 注册服务。我发现以下所有方法都有效,这是正确的方法吗?每个人的情况是什么?

public class AndroidInitializer : IPlatformInitializer
{
    static OpenAppService openAppService = new OpenAppService();

    public void RegisterTypes(IContainerRegistry containerRegistry)
    {
        containerRegistry.RegisterInstance<IOpenAppService>(openAppService);

        containerRegistry.Register<IFacebookLoginService, FacebookLoginService>();

        containerRegistry.RegisterSingleton<IAppleSignInService, AppleSignInService>();

    }
}

标签: c#prism

解决方案


First of all, what each of these methods does totally depends on the actual container used, especially when you go beyond the totally trivial things. That's probably the main cause why there's no documentation for this stuff.

That being said...

  • Register says that the given service should be used when the given interface is injected, and that a new instance will be created for each single injection.
  • RegisterSingleton differs in that the same instance is used for all injections.
  • RegisterInstance is the same as RegisterSingleton, but you have to provide an instance.

which is the correct way to do it? What is the case for each?

So, most of the time services are registered as singletons, because you want viewmodels to be able to communicate through the service. Example: the EventAggregator - when one view models publishes an event, you expect others to receive it, which is only possible if they subscribe using the same instance as the publisher publishes on. A WCF client, though, doesn't need to be a singleton, because the communication happens on the server side.

You don't want to register instances because this mixes up registration and resolving, and you have to make absolutely sure that all dependencies of the instance have been registered already when creating the instance to register it (through a call to Resolve, which in itself has a touch of evil). This is less of a problem if you register everything in one method, but becomes a lot more of a headache if you have multiple (interdependent) modules.


推荐阅读