如何在Contructor中通过传递参数来保留注册服务的使用情况?

问题描述 投票:0回答:1

我是有关OOP和IOC容器的新手。我需要了解如何使用去斑注射。我的应用程序的简单结构如下。

以下代码属于CacheService;

using Akavache;

    public class CacheService : ICacheService
    {
        protected IBlobCache Cache;

        public CacheService(IBlobCache blobCache, string applicationName)
        {
            Cache = blobCache;
            BlobCache.ApplicationName = applicationName;
        }
    }

我已经在App.cs中按以下方式注册了此服务,因为我需要使用两种不同类型的相同服务。

protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
    containerRegistry.RegisterSingleton<IMockApiService, MockApiService>();
    containerRegistry.RegisterSingleton<IEssentialsService, EssentialsService>();

    containerRegistry.RegisterInstance<CacheService>(new CacheService(BlobCache.LocalMachine, "MyAppName"), "LocalMachineCache");
    containerRegistry.RegisterInstance<CacheService>(new CacheService(BlobCache.UserAccount, "MyAppName"), "UserAccountCache");
}

我的ViewModel代码如下;

public class SettingsPageViewModel : BindableBase
{
    protected ICacheService CacheService { get; private set; }

    public SettingsPageViewModel(ICacheService cacheService)
    {
        CacheService = cacheService;
    }
}

以上用法是否可行?如果可能,应该如何修改我的结构?预先谢谢你。

xamarin.forms prism dryioc
1个回答
0
投票

据我所知,这种用法是not可能的,因为您的IOC容器不知道如何解析ICacheService,因为您将实例注册为CacheService。当DryIOC尝试解析SettingsPageViewModel时,它将遇到ICacheService并发现未注册的类型。至少这是Unity容器的行为。

无论如何,即使您将"LocalMachineCache""UserAccountCache"注册为ICacheService,即使[[if,我也怀疑这样做是否可行,因为对于DryIOC,没有办法知道将哪个与SettingsPageViewModel一起使用。 ,因此您必须定义要解决的问题。

根据其文档,Prism通过各自的参数名称解​​析依赖关系(除非我没有误解,see here)。假设您需要在设置中使用本地计算机缓存,则可以将其注册为"localMachineCache"(将其重命名以遵循SettingsPageViewModel的构造函数中的通用C#编码约定),并为该参数指定名称[>

containerRegistry.RegisterInstance<ICacheService>(new CacheService(BlobCache.LocalMachine, "MyAppName"), "localMachineCache"); containerRegistry.RegisterInstance<ICacheService>(new CacheService(BlobCache.UserAccount, "MyAppName"), "userAccountCache");

public SettingsPageViewModel(ICacheService localMachineCache)
{
    CacheService = localMachineCache;
}
因此,如果您同时需要这两者

public SettingsPageViewModel(ICacheService localMachineCache, ICacheService userAccountCache) { MachineCacheService = localMachineCache; UserAccountCacheService = userAccountCache; }

© www.soinside.com 2019 - 2024. All rights reserved.