Mam problemy z ASP.NET MVC 6 (wersja beta 4) próbując wstrzyknąć usługę w ramach filtru kontrolnego typu AuthorizationFilterAttribute
.Wstrzyknięcie zależności wewnątrz składnika FilterArt w ASP.NET MVC 6
Jest to usługa (to kolejna usługa wstrzykuje)
public class UsersTableRepository
{
private readonly NeurosgarContext _dbContext;
public UsersTableRepository(NeurosgarContext DbContext)
{
_dbContext = DbContext;
}
public ICollection<User> AllUsers
{
get
{
return _dbContext.Users.ToList();
}
}
//other stuff...
}
Jest to metoda ConfigureServices w klasie startowego dla usług umożliwiających
public void ConfigureServices(IServiceCollection services)
{
//...
services.AddSingleton<NeurosgarContext>(a => NeurosgarContextFactory.GetContext());
services.AddSingleton<UifTableRepository<Nazione>>();
services.AddSingleton<UsersTableRepository>();
}
Prosty „manekin” kontroler z dwoma filtrami zdefiniowane na tym. Możesz zauważyć, że już zrobiłem DI wewnątrz tego kontrolera, dekorując nieruchomość przy pomocy [FromServices]
i to działa.
[Route("[controller]")]
[BasicAuthenticationFilter(Order = 0)]
[BasicAuthorizationFilter("Admin", Order = 1)]
public class DummyController : Controller
{
[FromServices]
public UsersTableRepository UsersRepository { get; set; }
// GET: /<controller>/
[Route("[action]")]
public IActionResult Index()
{
return View();
}
}
robi to samo w ciągu BasicAuthenticationFilter
DI nie działa i przy starcie UserRepository
nieruchomość jest zerowy odniesienia.
public class BasicAuthenticationFilterAttribute : AuthorizationFilterAttribute
{
[FromServices]
public UsersTableRepository UsersRepository { get; set; }
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (!Authenticate(filterContext.HttpContext))
{
// 401 Response
var result = new HttpUnauthorizedResult();
// Add the header for Basic authentication require
filterContext.HttpContext.Response.Headers.Append("WWW-Authenticate", "Basic");
filterContext.Result = result;
//if (!HasAllowAnonymous(context))
//{
// base.Fail(context);
//}
}
}
// ...
}
Każdy pomysł na temat rozwiązania tego problemu?
Problem polega na tym, że jeśli użyję konstruktora w filtrze do wstrzyknięcia usługi, nie będę mógł przechwycić instancji atrybutu. –
To dlatego, że nie należy wstrzykiwać zależności w swoje atrybuty. Prosimy o uważne przeczytanie cytowanych artykułów. – Steven
Dziękuję. Zrobię to! –