私はASP.NET Core 2.0でルーティングを試しています。 I(単純なユニットテスト用)System.DateTime.UtcNow
機能をラップクラスASP.Net Core RouteBuilderとDependency Injection
public interface IDateTimeWrapper
{
DateTime UtcNow();
}
public sealed class DateTimeWrapper : IDateTimeWrapper
{
public DateTime UtcNow()
{
return DateTime.UtcNow;
}
}
を持っているこれはHttpResponse
public class WhatIsTheTimeHandler
{
private readonly IDateTimeWrapper _dateTimeWrapper;
public WhatIsTheTimeHandler(
IDateTimeWrapper dateTimeWrapper)
{
this._dateTimeWrapper = dateTimeWrapper;
}
public async Task Execute(Microsoft.AspNetCore.Http.HttpContext httpContext)
{
httpContext.Response.StatusCode = 200;
await httpContext.Response.WriteAsync(this._dateTimeWrapper.UtcNow().ToString());
}
}
に
DateTimeWrapper
の結果を書き込み、単一方法
Execute
を持つクラスによって使用されています
の中で へのリクエストは、WhatIsTheTimeHandler
(!!!コメントを参照)で処理されます。
public sealed class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder();
builder.SetBasePath(env.ContentRootPath);
builder.AddJsonFile("appsettings.json", false, true);
// we must lowercase the json file path due to linux file name case sensitivity
builder.AddJsonFile($"appsettings.{env.EnvironmentName.ToLower()}.json", false, true);
builder.AddEnvironmentVariables();
this.Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
public void ConfigureServices(IServiceCollection services)
{
services.AddRouting();
services.AddScoped<IDateTimeWrapper, DateTimeWrapper>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
var routeBuilder = new Microsoft.AspNetCore.Routing.RouteBuilder(app);
// !!!
// I want to do something like
// routeBuilder.MapGet("whatisthetime", WhatIsTheTimeHandler.Execute);
var routes = routeBuilder.Build();
app.UseRouter(routes);
}
}
WhatIsTheTimeHandler.Execute
がインスタンスメソッドであるため、上記の操作はできません。私。エラー:
An object reference is required for the non-static field, method or property 'WhatIsTheTimeHandler.Execute(HttpContext)' Cannot access non-static method in static context).
私はそれstatic
作るなら、私は_dateTimeWrapper
インスタンスメンバを使用することはできません。
アイデア?
httpsのミドルウェアを作成します://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware?tabs = aspnetcore2xまた、DIを許可します – Nkosi
'WhatIsTheTimeHandler'がなぜ' Controller'ではないのだろうか? –
@CamiloTerevintoは非常に有効なポイントを作っています。 – Nkosi