我是有关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;
}
}
以上用法是否可行?如果可能,应该如何修改我的结构?预先谢谢你。
据我所知,这种用法是not可能的,因为您的IOC容器不知道如何解析ICacheService
,因为您将实例注册为CacheService
。当DryIOC尝试解析SettingsPageViewModel
时,它将遇到ICacheService
并发现未注册的类型。至少这是Unity容器的行为。
无论如何,即使您将"LocalMachineCache"
和"UserAccountCache"
注册为ICacheService
,即使[[if,我也怀疑这样做是否可行,因为对于DryIOC,没有办法知道将哪个与SettingsPageViewModel
一起使用。 ,因此您必须定义要解决的问题。
"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;
}