配置您的Startup.cs:
public void ConfigureServices(IServiceCollection services) {
...
services.AddSingleton<ISessionFactory>(c => {
var config = new Configuration();
...
return config.BuildSessionFactory();
});
...
services.AddSingleton<RoleServico>();
...
}
然後,在你的API控制器使用這樣的:
[Route("api/role")]
public class RoleController : Controller {
private readonly ISessionFactory SessionFactory;
private readonly RoleServico RoleServico;
public RoleController(ISessionFactory sessionFactory, RoleServico roleServico) {
if (sessionFactory == null)
throw new ArgumentNullException("sessionFactory");
SessionFactory = sessionFactory;
this.RoleServico = roleServico;
}
[HttpGet]
public IList<RoleModel> Get() {
IList<RoleModel> model = new List<RoleModel>();
using (var session = SessionFactory.OpenSession())
using (var transaction = session.BeginTransaction()) {
return RoleServico.SelecionarRoles(session);
}
}
}
你Startup.cs看起來不錯,但我不知道你怎麼」重新使用你的注入類,或者,如果你得到一些錯誤信息。
「RoleServico」是類庫項目中的類(與您的情況類似)。在我的情況下,我使用「Singleton」,但它是「Scoped」的相同配置。我不能評論你的問題,並要求提供更多信息(我沒有50聲望)。
您的UsersRepo本身是否需要依賴關係,並且該依賴關係尚未註冊? 您應該能夠獲得有助於指出的錯誤消息。 –
@MikeD,這個回購沒有新東西。我曾經多次創建它,並且像以前一樣,我期望應用DI容器將Repo實例注入到控制器中。 –
通常repos需要一個dbContext類型的對象,你確定你的repo在它自己的構造函數中沒有任何參數? –