0

我想給它的接口分配一個類。我正在使用工作單元模式。如何動態地將未指定的類分配到未指定的接口中?

我們假設我們的數據庫中有多個表格,並且我們用類指定了這些表格。我提到了其中兩個。我想訪問任何控制器上的多個表,但我不知道如何將這些表(類)集成到接口中。

如何在控制器中動態分配FirmApiProcessor,CompanyApiProcessor到它們的接口?我想給它們分配是這樣的:

ICompanyApi _companyApi = CreateProcessor(param); 

這樣的:而不是

ICompanyApi _companyApi = CreateProcessor(ICompanyApi); 

IFirmApi _firmApi = CreateProcessor(IFirmApi); 

ICompanyApi _companyApi = new CompanyApiProcessor(uow); 

IFirmApi _firmApi = new FirmApiProcessor(uow); 

我的接口:

public interface <Api<T> where T : BaseDto 

public interface IParameterApi : IApi<ParameterDto> 

public interface IFirmApi : IApi<FirmDto> 

我的課:

public class BaseApiProcesssor<TDto, TEntity> : IApi<TDto> where TDto : BaseDto where TEntity : BaseEntity 

public class CompanyApiProcessor : BaseApiProcesssor<CompanyDto, Company>, IParameterApi 

public class CompanyController : Controller 
{ 
    ICompanyApi _companyApi; 
    IFirmApi _firmApi; 

    public CompanyController(IUnitOfWork uow) // uow is created by dependency injection 
    { 
     // How to assign ?? 
     // 
     //I can assign them like this. But this is not dynamic and not logical to use like this. 

     // _companyApi = new CompanyApiProcessor(uow); 
     // _firmApi = new FirmApiProcessor(uow); 

     _companyApi = ??????? 
     _firmApi = ???????? 
    } 
} 

public class FirmApiProcessor : FirmApiProcesssor<FirmDto, Firm>, IFirmApi 

public class FirmController : Controller 
{ 
    IFirmApi _firmApi; 

    public FirmController(IUnitOfWork uow) 
    { 
     // How to assign ?? 
     // 
     //I can assign it like this. But this is not dynamic and not logical to use like this. 

     // _firmApi = new FirmApiProcessor(uow); 

     _firmApi = ???????? 
    } 
} 

回答

0

你真的需要依賴注入容器,但你可以保持它的簡單,並按照這個例子:

ICompanyApi _companyApi = CreateProcessor<ICompanyApi>(); 
IFirmApi _firmApi = CreateProcessor<IFirmApi>(); 

public static T CreateProcessor<T>() 
{ 
    if (T is ICompanyApi) 
    { 
     return new CompanyApiProcessor() as T; 
    } 
    else if (T is IFirmApi) 
    { 
     return new FirmApiProcessor() as T; 
    } 
    else 
    { 
     throw new ApplicationException("Unsupported type"); 
    } 
} 

編輯:如果你不想定義映射,您可以嘗試使用反射找到接口實現者:

public static T CreateProcessor<T>() 
{ 
    var types = AppDomain.CurrentDomain.GetAssemblies() 
     .SelectMany(r => r.GetTypes()) 
     .Where(r => type.IsAssignableFrom(T)); 

    var type = types.FirstOrDefault(); // Selecting first found implementor 
    if (type == null) 
     throw new ApplicationException("Unsupported type"); 

    return Activator.CreateInstance(type) as T; 
} 

爲了避免每次掃描您的組件,您可以添加一個詞典並記住映射。

+0

但假設我有100班。公司和公司有兩類。我需要動態分配它。 –

+0

@ŞerefCanMuştu你可以使用'Reflection'來掃描你的程序集以獲得接口的實現,但這可能會很慢。 – opewix

+0

@ŞerefCanMuştu請參閱我編輯的反射示例 – opewix