如何使用ASP.NET Core MVC内置依赖注入框架手动解析类型?
设置容器很容易:
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddTransient<ISomeService, SomeConcreteService>();
}
Run Code Online (Sandbox Code Playgroud)
但是如何在ISomeService不进行注射的情况下解决?例如,我想这样做:
ISomeService service = services.Resolve<ISomeService>();
Run Code Online (Sandbox Code Playgroud)
没有这样的方法IServiceCollection.
我正在使用 asp.net-core v1.1.0 :)
我想从服务类而不是从控制器访问应用程序设置值,我的代码是:
应用程序设置.json
// appsettings.json
{
"ImagesDBSettings": {
"Endpoint": "",
"Key": "",
}
}
Run Code Online (Sandbox Code Playgroud)
启动.cs
// Startup.cs
...
public void ConfigureServices(IServiceCollection services)
{
...
services.AddOptions();
services.Configure<ImagesDBSettings>(Configuration.GetSection("ImagesDBSettings"));
...
}
...
Run Code Online (Sandbox Code Playgroud)
ImagesDBSettings.cs
// ImagesDBSettings.cs
public class ImagesDBSettings
{
public string Endpoint { get; set; }
public string Key { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
ImagesDBService.cs
// ImagesDBService.cs
public class ImagesDBService
{
private readonly ImagesDBSettings _settings;
public ImagesDBService(IOptions<ImagesDBSettings> settings)
{
_settings = settings.Value;
}
}
Run Code Online (Sandbox Code Playgroud)
编译时我收到错误:
没有给出与“ImagesDBService.ImagesDBService(IOptions)”所需的形式参数“设置”相对应的参数
关于如何使依赖注入工作有什么想法吗?
我想使用简单的LINQ命令从我的表"Header"中选择数据,但我遇到了错误.
我的行动
public HeaderModel GetHeaderInformation()
{
using(var context = new ApplicationDbContext())
{
var header = context.Headers.Select(x => new HeaderModel
{
colorCode = x.colorCode,
height = x.height,
Id = x.Id,
left = x.left,
top = x.top,
width = x.width
}).FirstOrDefault();
return header;
}
}
Run Code Online (Sandbox Code Playgroud)
错误
附加信息:尚未为此DbContext配置数据库提供程序.可以通过覆盖DbContext.OnConfiguring方法或在应用程序服务提供程序上使用AddDbContext来配置提供程序.如果使用AddDbContext,那么还要确保您的DbContext类型在其构造函数中接受DbContextOptions对象,并将其传递给DbContext的基础构造函数.
我的ApplicationDbContext
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options) { }
public ApplicationDbContext() : base() { }
public DbSet<Header> Headers { get; set; }
public DbSet<Menu> Menus { get; set; }
} …Run Code Online (Sandbox Code Playgroud)