问题描述
我是DI和IoC的新手,并且遇到接口解析问题。
技术:WPF,C#,Unity容器
我尝试通过模型类型动态显示通用网格,这些将定义当我在其中过滤数据时要调用的正确服务的分辨率。我这样做是因为我要进入的项目有近100个业务对象。我不会为每个视图创建一个视图/视图模型/界面。
因此,在模型中,我有例如:CustomerModel / OrderModel / ... 在我的服务中:CustomerService和ICustomerService / OrderService和IOrderService / ...,我的所有服务也都从IBaseService继承,其中T是模型。 像这样:
//For the service call
public interface IBaseService<TModel>
{
Task<IEnumerable<TModel>> GetWithFilter(string filterQuery);
}
public interface ICustomerService : IBaseService<CustomerModel>
{
IEnumerable<CustomerModel> Get(string filterQuery);
//...
}
public class CustomerService : ICustomerService
{
// Inherit form IBaseService<TModel>
public IEnumerable<CustomerModel> GetWithFilter(string filterQuery)
{
return Get(filterQuery); //
}
// Inherit from ICustomerService
public IEnumerable<CustomerModel> Get(string filterQuery = null)
{
// some code
// return IEnumerable<CustomerModel>
}
}
//A part of the generic ViewModel
public class UC_GridViewModel<TModel> : BaseViewModel,IUC_GridViewModel<TModel>
{
private IBaseService<TModel> _modelService;
public IBaseService<TModel> ModelService
{
get { return _modelService; }
set { Set(ref _modelService,value); }
}
private ObservableCollection<TModel> _sourceItem;
public ObservableCollection<TModel> SourceItem
{
get { return _sourceItem; }
set { Set(ref _sourceItem,value); }
}
[InjectionConstructor]
public UC_GridViewModel(IEnumerable<TModel> sourceItem,IBaseService<TModel> modelService)
{
_sourceItem = new ObservableCollection<TModel>(sourceItem);
_modelService = modelService;
}
// This is called by a command
public void FilterGridCommand(string filterQuery)
{
_sourceItem = _modelService.GetWithFilter(filterQuery);
}
}
//In IoC Container (Resolver layer bind to Unity Container)
DependencyResolver.RegisterType(typeof(IBaseService<CustomerModel>),typeof(CustomerService));
DependencyResolver.RegisterType<ICustomerService,CustomerService>();
DependencyResolver.RegisterType(typeof(IUC_GridViewModel<>),typeof(UC_GridViewModel<>));
我除了: 如果实例化一个UC_GridViewModel,我将从CustomerService类型中获取一个ModelService,它将执行从IBaseService继承的方法。
运行解决方案时,我得到了:
ResolutionFailedException: Resolution failed with error: No public constructor is available for type API_Caller.IBaseService`1
InvalidOperationException: No public constructor is available for type API_Caller.IBaseService`1[BO_Models.CustomerModel].
那么在这种情况下如何解决我的IBaseService以避免这些错误?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)