[英]StructureMap and .Net Core
我正在创建一个准系统.NET Core Web API项目(从下面的空白模板开始) https://andrewlock.net/removing-the-mvc-razor-dependencies-from-the-web-api-template-in-asp-网络核心/
直到我添加了StructureMap,下面的代码才能正常工作。 现在,我收到此错误。
StructureMap.StructureMapConfigurationException:没有注册默认实例,并且无法自动确定类型'System.IServiceProvider'的实例
没有为System.IServiceProvider指定配置
1.)Container.GetInstance()
在WebApplication4.Startup.ConfigureServices(IServiceCollection服务)的StructureMap.Container.GetInstanceT处的StructureMap.SessionCache.GetDefault(Type pluginType,IPipelineGraphpipelineGraph)处-从上一个引发异常的位置开始的堆栈跟踪-在System.Runtime处Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection服务)的.ExceptionServices.ExceptionDispatchInfo.Throw()Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()的Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()的Microsoft.AspNetCore.Hosting。
有任何想法吗?
请注意:我们没有使用builder.AppMvc()
因为我们正在尝试尽可能缩小此api。
这是相关的代码。
public IServiceProvider ConfigureServices(IServiceCollection services)
{
var builder = services.AddMvcCore();
builder.AddApiExplorer();
builder.AddAuthorization();
builder.AddFormatterMappings();
builder.AddJsonFormatters();
builder.AddCors();
// Register the Swagger generator, defining one or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
});
var container = ContainerConfigurator.Configure();
return container.GetInstance<IServiceProvider>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
app.UseMvc();
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
}
public class ContainerConfigurator
{
public static Container Configure()
{
var container = new Container(
x => x.Scan
(
s =>
{
s.TheCallingAssembly();
s.WithDefaultConventions();
s.AddAllTypesOf<IStartupTask>();
s.LookForRegistries();
s.AssembliesAndExecutablesFromApplicationBaseDirectory();
}
)
);
return container;
}
}
您忘记了使用服务集合填充容器,这就是为什么容器不知道如何解析IServiceProvider
。
添加x.Populate(services);
行,其中services
是您在ConfigureServices
方法中拥有的IServiceCollection
的实例。 这样的事情应该起作用:
public static Container Configure(IServiceCollection services)
{
var container = new Container( config =>
{
config.Scan(s =>
{
s.TheCallingAssembly();
s.WithDefaultConventions();
s.AddAllTypesOf<IStartupTask>();
s.LookForRegistries();
s.AssembliesAndExecutablesFromApplicationBaseDirectory();
});
config.Populate(services);
});
return container;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.