我遇到一个问题,无法在我的应用程序中将依赖项注入与IOptions
构造一起使用。这是在使用多个项目时。
我正在使用带有以下类的StructureMap:
namespace Core
{
public class SquareConfiguration
{
public string AccessToken { get; set; }
public string LocationId { get; set; }
public string ApplicationId { get; set; }
}
}
还有我的appsettings.json
{
"Square": {
"AccessToken": "sandbox-sq0atb-9uDBLTDYMn1TSEFUlOrU_g",
"LocationId": "CBASEEW9Mi6K3Og-8kZaJ4cRODggAQ",
"ApplicationId": "sandbox-sq0idp-hytewYq7V-YZkSGsSAit4A"
},
}
在 Startup.cs
中namespace Web
{
public class Startup
{
private IServiceCollection _services;
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_1);
// Configuration
services.AddOptions();
services.Configure<SquareConfiguration>(Configuration.GetSection("Square"));
// Application Services
var container = new Container();
container.Configure(config =>
{
config.Scan(i =>
{
i.AssemblyContainingType(typeof(Startup)); // Web
i.AssemblyContainingType(typeof(BaseEntity)); // Core
i.Assembly("Infrastructure"); // Infrastructure
i.WithDefaultConventions();
i.ConnectImplementationsToTypesClosing(typeof(IHandle<>));
i.ConnectImplementationsToTypesClosing(typeof(IRender<>));
});
config.For(typeof(IRepository<>)).Add(typeof(EfRepository<>));
config.Populate(services);
});
return container.GetInstance<IServiceProvider>();
}
}
}
最后是一个注入IOptions的剃刀页面:
namespace Web.Pages.Basket
{
public class CheckoutModel : PageModel
{
public string ApplicationId { get; set; }
public string LocationId { get; set; }
public CheckoutModel(IOptions<SquareConfiguration> squareConfiguration)
{
var config = squareConfiguration.Value;
ApplicationId = config.ApplicationId;
LocationId = config.LocationId;
}
}
}
因此,当我导航到页面时,会收到错误消息
InvalidOperationException:尝试激活“ Web.Pages.Basket.CheckoutModel”时,无法解析类型为“ Microsoft.Extensions.Options.IOptions`1 [Core.SquareConfiguration]”的服务。
更新:添加了services.AddOptions();到startup.cs