我得到了一个任务,其中包含创建一个.Net 4.8应用程序;HttpSelfHostServer";。我陷入了分配";IServiceCollection服务";以配置。DependencyResolver(类型为System.Web.Http.Delations.IDependencySolutionr(
我真的不想使用autofac或其他框架,但我能找到的所有指南都指向这些框架。微软不是提供了一条出路吗?
我只需要解决同样的问题。我就是这样做的:
首先,我创建了一个新的facade类,将IServiceCollection
从主机生成器映射到HttpSelfHostConfiguration
支持的接口:
using System;
using System.Collections.Generic;
using System.Web.Http.Dependencies;
using Microsoft.Extensions.DependencyInjection;
namespace IntegrationReceiver.WebApi
{
public class HttpSelfHostDependencyResolver : IDependencyResolver
{
private readonly IServiceProvider sp;
private readonly IServiceScope scope;
public HttpSelfHostDependencyResolver(IServiceProvider sp)
{
this.sp = sp;
this.scope = null;
}
public HttpSelfHostDependencyResolver(IServiceScope scope)
{
this.sp = scope.ServiceProvider;
this.scope = scope;
}
public IDependencyScope BeginScope() => new HttpSelfHostDependencyResolver(sp.CreateScope());
public void Dispose() => scope?.Dispose();
public object GetService(Type serviceType) => sp.GetService(serviceType);
public IEnumerable<object> GetServices(Type serviceType) => sp.GetServices(serviceType);
}
}
这需要我根据这里的答案获得最新的NuGet包Microsoft.Extensions.DependencyInjection.Abstractions
:我如何查看.NET IServiceProvider可以提供的所有服务?
然后,我在服务提供商中注册了我的HttpSelfHostServer
,代码为:
services.AddSingleton(sp => new HttpSelfHostDependencyResolver(sp));
services.AddSingleton(sp =>
{
//Starting the HttpSelfHostServer with user-level permissions requires to first run a command like
// netsh http add urlacl url=http://+:8080/ user=[DOMAINNAME][USERNAME]
var config = new HttpSelfHostConfiguration("http://localhost:8080");
config.Routes.MapHttpRoute("API Default", "api/{controller}/{id}", new { id = RouteParameter.Optional });
config.DependencyResolver = sp.GetRequiredService<HttpSelfHostDependencyResolver>();
return new HttpSelfHostServer(config);
});
最后,为了找到我的ApiController,我也必须在服务提供商那里注册。我只是用
services.AddScoped<HealthCheckController>();
对于brewity,我只是在下面包含我的api控制器,以说明它现在是如何获得依赖项的:
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
namespace IntegrationReceiver.WebApi
{
public class HealthCheckController : ApiController
{
private readonly ServiceBusRunner serviceBusRunner;
public HealthCheckController(ServiceBusRunner serviceBusRunner)
{
this.serviceBusRunner = serviceBusRunner;
}
[HttpGet]
public async Task<HttpResponseMessage> Get()
{
var response = new
{
serviceBusRunner.RunningTasks,
serviceBusRunner.MaxRunningTasks
};
return await Json(response)
.ExecuteAsync(System.Threading.CancellationToken.None);
}
}
}
这是一个非常愚蠢的实现,但在我可以将此代码升级到net5之前,它对我有效。
我希望它也能帮助你!