如果你用模板生成一个应用程序,你会在Startup类上有这样的东西:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc();
}
然后你可以在那里添加依赖项,例如:
services.AddTransient<ITestService, TestService>();
如果你想在你的控制器上访问ITestService,你可以在构造函数上添加IServiceProvider,它将被注入:
public HomeController(IServiceProvider serviceProvider)
然后你可以解析你添加的服务:
var service = serviceProvider.GetService<ITestService>();
注意,要使用通用版本,你必须包含扩展名的命名空间:
using Microsoft.Extensions.DependencyInjection;
ITestService.cs
public interface ITestService
{
int GenerateRandom();
}
TestService.cs
public class TestService : ITestService
{
public int GenerateRandom()
{
return 4;
}
}
Startup.cs (ConfigureServices)
public void ConfigureServices(IServiceCollection services)
{
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc();
services.AddTransient<ITestService, TestService>();
}
HomeController.cs
using Microsoft.Extensions.DependencyInjection;
namespace Core.Controllers
{
public class HomeController : Controller
{
public HomeController(IServiceProvider serviceProvider)
{
var service = serviceProvider.GetService<ITestService>();
int rnd = service.GenerateRandom();
}