简体   繁体   中英

Conditional dependency resolving per request in ASP.NET Web Api 2

I'm currently working on a Rest API using asp.net Web Api (5.0.0-rc1). By now we don't use any DI container, so it's Poor Man's DI. But the plan is to use one or another soon.

In order to resolve our dependencies we use our own implementation of IHttpControllerActivator similar to how it is described in Mark Seemann's blog .

The problem

All our controllers use services in order to perform their actions. We're also trying to reuse controllers for different roles. Fe a controller that lists all users has the HttpGet attribute

[HttpGet("api/role/{role}/users")]

So depending on the role in the uri (could be fe admin or department ) we want to resolve the controller's dependencies differently. This could mean, that we want to wrap a service with a decorator or we need to inject a some kind of strategy`into the service depending on the role.

Note: The conditional resolving of a dependency could be deep down in the dependency graph.

The question

Since I'm quite new to dependency injection I'm really unsure what's the standard way to resolve conditional dependencies. Is dependency injection meant to be conditional on a per request base or is the dependency graph rather fixed and we should use factories in this case? Fe a controller gets ISomeServiceFactory instead of a ISomeService and the factory itself gets the role injected.

I also took a look at Castle Windsor's Typed Factory Facility , but I'm not sure if that would solve our problem.

There are various ways you translate a run-time value to one among several available dependencies (and entire sub-graphs). Instead of relying on factories, I rather prefer selecting among available dependencies.

So far, I've identified at least three different ways of doing this:

Of these, I personally prefer Partial Type Name , because it's the most loosely coupled.

All these selection strategies rely on all of the strategy instances being available before selection. Often, that's not a problem, because if they're thread-safe, a single instance of each can be reused across all HTTP requests.

However, even if one or more of the services aren't thread-safe, there are ways to deal with potential performance issues - most notably using the Virtual Proxy pattern.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM