我有一個通用介面IViewModelService.cs
public interface IViewModelService<T> where T : class
{
public Task<T> Get(); // returns a view model
}
這是由兩種不同的視圖模型服務實作的,我假設它們是封閉型別:
public class HomeViewModelService : IViewModelService<HomeViewModel>
{
public HomeViewModelService()
{
// Dependency injection for Db Context here
}
public async Task<HomeViewModel> Get()
{
//requires some async _dbContext logic
return new HomeViewModel(); // for testing purposes
}
}
和
public class ProfileViewModelService : IViewModelService<ProfileViewModel>
{
public ProfileViewModelService()
{
// Dependency injection for Db Context here
}
public async Task<ProfileViewModel> Get()
{
//requires some async _dbContext logic
return new ProfileViewModel(); // for testing purposes
}
}
一直在研究依賴注入,我想知道如何將這些服務實作到 Startup.cs 中。我試過這些:
services.AddTransient(typeof(IViewModelService<>), typeof(HomeViewModelService));
// ERROR: Open generic service type 'IViewModelService`1[T]' requires registering an open generic implementation type. (Parameter 'descriptors')'
services.AddTransient(typeof(IViewModelService<HomeViewModelService>), typeof(HomeViewModelService));
// ERROR: Implementation type 'HomeViewModelService' can't be converted to service type 'IViewModelService`1[HomeViewModelService]'
services.AddScoped<IViewModelService<HomeViewModelService>, HomeViewModelService>();
// ERROR: This type cannot be used as a type parameter 'TImplementation' in the generic type or method.
// There is no implicit reference conversion from HomeViewModelService to IViewModelService<HomeViewModelService>
uj5u.com熱心網友回復:
嘗試
services.AddScoped<IViewModelService<HomeViewModel>, HomeViewModelService>();
閱讀
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/494900.html
標籤:C# 网 asp.net-mvc asp.net 核心 asp.net-mvc-3
上一篇:如何在androidjetpackcompose的文本欄位中設定數字限制?
下一篇:如何將按鈕單擊作為函式引數傳遞?
