.Net Core DI从启动过滤类

时间:2016-12-05 15:13:02

标签: asp.net-web-api dependency-injection asp.net-core

如何将数据库注入我的TestAttribute类,因为.net核心对我的控制器有神奇的作用。

    services.AddScoped<DbContextOptions>(p => p.GetRequiredService<DbContextOptions<Context>>());
    services.TryAdd(new ServiceDescriptor(typeof(Context), typeof(Context), ServiceLifetime.Transient));

    services.AddMvc(options =>
    {
        options.Filters.Add(new TestAttribute(/*need parameter*/));
    }

    public HouseController([FromServices] Context database)
    {
        this.Database = database;
    }

    public class TestAttribute : ActionFilterAttribute
    {
        public TestAttribute([FromServices] Context database)
        {
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
        }
}

0 个答案:

没有答案