![](/img/trans.png)
[英]In Xamarin Forms UnityServiceLocator namespace not found (Unity Dependency Injection & IoC containers)
[英]Unity Extending Dependency Injection Containers
我正在開發一個當前在整個代碼中都使用Service Locator Anti-Pattern的項目。 我正在開始逐步將所有內容轉換為使用依賴注入的過程,但是由於項目規模龐大,我希望在一段時間內做到這一點。
我有一個自定義工廠,其自定義實現中注冊了100多個依賴項。 因此,我只想將容器包裝成統一的,如果我當前的容器沒有實現,則退回使用統一。
我已經編寫了此類來包裝IUnityContainer
public class GlobalFactoryUnityWrapper : IUnityContainer
{
IUnityContainer _unityContainer = new UnityContainer();
IUnityContainer _parent;
public GlobalFactoryUnityWrapper(IUnityContainer parent = null)
{
this._parent = parent ?? this._unityContainer.Parent;
}
public IUnityContainer Parent => this._parent;
//... Other IUnityContainer members
public object Resolve(Type type, string name, params ResolverOverride[] resolverOverrides)
{
if(GlobalContext.InstanceFactory.CanGetInstance(type))
{
return GlobalContext.InstanceFactory.GetInstance(type);
}
return this._unityContainer.Resolve(type, name, resolverOverrides);
}
}
我在這里為我的控制器注冊了大多數依賴項,但是控制器本身沒有,所以回退了使用unity的容器。
編輯我認為我使用的是錯誤的東西,應該使用策略。 我的主要目標是如果容器不包含實現,請回退使用舊容器中注冊的內容
我需要創建一個后備策略,這可能不是最理想的代碼,但目前可以使用
public class FactoryFallbackExtension : UnityContainerExtension
{
public FactoryFallbackExtension()
{
}
protected override void Initialize()
{
var strategy = new FallBackStrategy(Context);
Context.Strategies.Add(strategy, UnityBuildStage.PreCreation);
}
}
public class FallBackStrategy : BuilderStrategy
{
private ExtensionContext baseContext;
public FallBackStrategy(ExtensionContext baseContext)
{
this.baseContext = baseContext;
}
public override void PreBuildUp(IBuilderContext context)
{
var key = context.OriginalBuildKey;
if (key.Type.IsInterface)
{
if(GlobalContext.InstanceFactory.CanGetInstance(key.Type))
context.Existing = GlobalContext.InstanceFactory.GetInstance(key.Type);
}
}
}
然后,當我配置容器時,我可以像下面這樣添加Container擴展:
public static void Configure()
{
var container = new UnityContainer();
RegisterDepedencies(container);
container.AddExtension(new FactoryFallbackExtension());
GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
SetControllerFactory(container);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.