Controller中的ASP.NET Core MVC FromService绑定返回空集合 [英] ASP.NET Core MVC FromService binding in Controller returns empty collection

查看:82
本文介绍了Controller中的ASP.NET Core MVC FromService绑定返回空集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管试图将ASP.NET Core MVC注册为Singleton,但在尝试使用ASP.NET Core MVC时却陷入了依赖注入,从而在我的控制器操作中返回了空集合.尝试了两种不同的注册方式,但实际上只有一种有效.所述方法如下:

Been trying to get a grip of ASP.NET Core MVC but got stuck with dependency injection returning empty collection in my controller action, despite of registering the service as Singleton in ConfigureService method. Tried two different ways to register but only one of them actually works. Said method is as following:

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();
    /***THIS DOES NOT WORK***/
    services.AddSingleton<IRepository<Employee>, EmployeeRepository>();
    var empRepo = services.BuildServiceProvider().GetService<IRepository<Employee>>();
    empRepo.Create( "emp001" );

    /***THIS WORKS***/
    var employeeRepository = new EmployeeRepository();
    employeeRepository.Create( "emp001" );
    services.AddSingleton<EmployeeRepository>( employeeRepository );
}

以下是我的控制器操作:

And following is my Controller action:

[HttpGet( "{empID}" )]
public string GetEmployee( string empID, [FromServices] IRepository<Employee> employees **/*THIS IS ALWAYS EMPTY*/**)
{
    ....
}

请指出正确的方向.两种AddSingleton方法之间有什么区别?如何通过控制器动作的DI使用第一种方法来访问服务? TIA.

Kindly point me in the right direction. What is the difference between the two AddSingleton methods? How can I access the service using 1st approach by DI on Controller action? TIA.

推荐答案

我不得不回到我唯一可行的选择,这是 @Daniel J.G.建议使用的选项;初始化存储库后,AddSingleton<T>()(以及他的一些有用技巧).不过,我希望初始化后再使用其他选项.

I had to fall back to the only working option for me which is what @Daniel J.G. suggested to use; the AddSingleton<T>() after having initialised the repository (along with some useful tips from him). Though, I would have liked to have the other option work after initialisation.

这篇关于Controller中的ASP.NET Core MVC FromService绑定返回空集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆