【发布时间】:2018-01-18 04:11:06
【问题描述】:
我正在尝试使用 Autofac 在 .Net Core 2.0 WebApi 应用程序上使用拦截,但我无法在控制器上成功。我尝试的是
首先我创建了一个基本的 webapi,它有一个默认控制器(ValuesController)。然后我如下设置autofac配置。项目工作没有任何错误,但拦截似乎没有运行。我做错了什么?
Startup.cs
public void ConfigureContainer(ContainerBuilder builder)
{
builder.Register(c => new CallLogger());
builder.RegisterType<ValuesController>()
.EnableClassInterceptors()
.InterceptedBy(typeof(CallLogger));
}
CallLogger.cs
public class CallLogger : IInterceptor
{
public CallLogger()
{
System.Console.WriteLine("XXXXX");
}
public void Intercept(IInvocation invocation)
{
Console.WriteLine($"Calling method {invocation.Method.Name} with parameters {(string.Join(", ", invocation.Arguments.Select(a => (a ?? "").ToString()).ToArray()))}... ");
invocation.Proceed();
Console.WriteLine("Done: result was {0}.", invocation.ReturnValue);
}
}
ValuesController.cs
[Route("api/[controller]")]
[Intercept(typeof(CallLogger))]
public class ValuesController : Controller
{
private readonly ITest _test;
public ValuesController(ITest test)
{
_test = test;
}
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("{id}")]
public string Get(int id, [FromHeader(Name = "TenantId")] string tenantId)
{
_test.Log("asdasdasda");
return tenantId + " => " + id;
}
// POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
【问题讨论】:
-
请参阅this answer。默认情况下,控制器不通过 DI 解析。您必须在 MvcBuilder 上调用
AddControllersAsService()才能将控制器注册为服务。只有这样 Autofac 才会进行解析。没有它,ASP.NET Core 将检查构造函数并从您的 IoC 容器中手动解析依赖项 -
使用这种
EnableClassInterceptors是脆弱的,因为忘记创建成员virtual会跳过你的拦截器并使你的应用程序“静默失败”。相反,您最好使用中间件组件来应用日志记录,这样可以保证运行。
标签: c# asp.net-core autofac interceptor asp.net-core-webapi