MVC 5 / UnityConfig-相同的接口-多种实现

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

所以我有这个基本接口:

public interface ISearchable
{
    List<AutocompleteResult> Search(string term);
}

和两个实现此接口的类:

头等舱:

public class LandlordReader :ISearchable
{
    public List<AutocompleteResult> Search(string term)
    {
        ....
    }
}

第二类:

public class CityReader : ISearchable
{
    public List<AutocompleteResult> Search(string term)
    {
       ....
    }
}

从现在开始,我处于黑暗之中...在UnityConfig.cs中,我尝试通过给它们命名来注册它们:

public static void RegisterTypes(IUnityContainer container)
{
    container.RegisterType<ISearchable, CityReader>("City");
    container.RegisterType<ISearchable, LandlordReader>("Landlord");
}

在MVC控制器中,我不知道要指定什么(在构造器中)-告诉我我想要一个或另一个:

public LandlordController(ISearchable searcher)
{
    // I want the LandlordReader here, but in the CityController, I want the CityReader....
    this.searcher = searcher;
}

关于DI和UnityInjector,我还是个菜鸟,所以一个完整的工作示例将是不错的。到目前为止,我有很多建议(使用通用接口,使用统一工厂)-但我自己尝试,没有用。

我知道在ASP.NET Core中有一个可以直接在构造函数的参数列表中指定的属性,但是我目前正在MVC5中工作。

谢谢。完成了很长的帖子。 ew。

c# asp.net asp.net-mvc dependency-injection unity-container
1个回答
1
投票

如果适合您的情况,可以尝试以下选项之一。

1

使用命名服务注入

public static void RegisterTypes(IUnityContainer container)
{
    container.RegisterType<ISearchable, CityReader>("City");
    container.RegisterType<ISearchable, LandlordReader>("Landlord");
}

public LandlordController([Dependency("Landlord")]ISearchable searcher)
{
    this.searcher = searcher;
}

2

public interface ISearchable<T> where T : class
{
//..............
}

public class LandlordReader : ISearchable<LandlordReader>
{
    public List<AutocompleteResult> Search(string term)
    {
        ....
    }
}

public class CityReader : ISearchable<CityReader>
{
    public List<AutocompleteResult> Search(string term)
    {
       ....
    }
}
public static void RegisterTypes(IUnityContainer container)
{
        container.RegisterType<ISearchable, CityReader>("City");
        container.RegisterType<ISearchable, LandlordReader>("Landlord");
}

然后在构造函数中使用时执行此操作

    private readonly ISearchable<CityReader> _cityReadersearcher;
    private readonly ISearchable<LandlordReader> _landLordsearcher;
    public LandlordController(ISearchable<CityReader> cityReadersearcher, 
     ISearchable<LandlordReader> landLordsearcher)
    {
         _cityReadersearcher= _cityReadersearcher;
        _landLordsearcher = landLordsearcher;
    }
© www.soinside.com 2019 - 2024. All rights reserved.