Autofac named service is not found in Web API Controller using attribute (Autofac.Extras.Attributed) - autofac

(Note: This is a simplified example intended to highlight the issue I'm seeing.)
I have a service I'm trying to register as a named service as follows:
builder.Register(new MyService()).Named<IMyService>("Test").SingleInstance();
I would have expected to be able to use this service in the constructor of my API Controller:
public TestController([WithKey("Test")] IMyService myService)
{
}
However, an exception gets thrown:
None of the constructors found with
'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type
'TestController' can be invoked with the available services and parameters:
Cannot resolve parameter 'IMyService myService' of constructor 'Void
.ctor(IMyService)'.
The same code as above works when I replace the .Named() call with a .As():
builder.Register(new MyService()).As<IMyService>().SingleInstance();
public TestController(IMyService myService)
{
}
It also seems to work when I keep the .Named() call, but add the .As() call to it first:
builder.Register(new MyService()).As<IMyService>().Named<IMyService>("Test")
.SingleInstance();
public TestController([WithKey("Test")] IMyService myService)
{
}
Any ideas on why this behaves as it does? Am I doing something wrong in how I register named services?

From the Autofac wiki:
That component will require you to register a keyed service with the specified name. You'll also need to register the component with the filter so the container knows to look for it.
var builder = new ContainerBuilder();
// Register the keyed service to consume
builder.RegisterType<MyArtwork>().Keyed<IArtwork>("Painting");
// Specify WithAttributeFilter for the consumer
builder.RegisterType<ArtDisplay>().As<IDisplay>().WithAttributeFilter();
...
var container = builder.Build();
Notice the WithAttributeFilter(). Try to add this to your RegisterControllers() call.

You need to use the [WithName] attribute not [WithKey]

Related

How can I change the name of the node AEM creates when a component is first dropped on the page?

I’m trying to figure out if it’s possible to customize the name of the node AEM creates when I first drop a component on the page.
The cq:Component node where my component is defined is named “knowledge-center-question” and when I drop it, AEM creates a node named “knowledge_center_que” in the page’s node tree using its default naming logic. I would prefer for the node name to be “question” when it is dropped (but I’d rather not rename the component itself).
It seems like this kind of thing must be possible given how customizable everything is in AEM, but I’m struggling to find an answer.
Take a look at :nameHints, which can be send as POST arguments to the SlingPostServlet: https://sling.apache.org/documentation/bundles/manipulating-content-the-slingpostservlet-servlets-post.html#algorithm-for-node-name-creation
You need to write a custom Sling post processor. Sling post processor is called after a component dropped in the page. Example code :
#Component(service = SlingPostProcessor.class, immediate = true, name = "com.aem.CustomPostProcessor")
public class CustomPostProcessor implements SlingPostProcessor {
#Override
public void process(SlingHttpServletRequest request, List<Modification> modifications) throws Exception {
if (accepts(request)) {
final Resource resource = request.getResourceResolver().getResource(request.getResource().getPath());
// Your logic
modifications.add(Modification.onCreated(resource.getPath()));
}
}
protected boolean accepts(SlingHttpServletRequest request) {
return "/my/resource/type".equals(request.getResource().getResourceType());
}
}

API versioning in ASP.NET Web API

I have an ASP.NET Web API I wrote and have published. Now that its out there we are looking at doing some improvements, and these improvements involve changes to certain calls which means we need to version to keep existing clients working.
I have used attribute routing so far in my app. Methods are invoked by: Controller/Action via RoutePrefix and Route attributes.
When I do need to create a V2 of my classes, I only want to recreate the classes that have actually changed, and redirect other routes back to v1 classes because they haven't changed. (Otherwise I just end up with a lot of boilerplate code, or duplicate code).
What I want to do is have the following routes work for my v1 version of classes:
Controller/Action
For V2 I want any new classes to go to V2, and any classes that haven't changed I want to return the HttpControllerDescriptor from V1 class. The route would look like v2/Controller/Action but would be redirected to Controller/Action.
I've implemented a IHttpControllerSelector and return the appropriate HttpControllerDescriptors but its not making the call into the method. I believe its because the routing information doesn't match the action. (When I put in an IHttpActionSelector and trace the exception it says "multiple actions were found that match the request).
So, I'm guess I'm wondering: Is this even possible? Is this the best way to achieve what I'm trying to do?
Here is what I implemented for versioning support in asp.net web api. Important to note I did not use attribute routing but explicit routes in WebApiConfig.cs so if you want to follow this pattern you would need to switch back to explicit routes. Also I do not prefer version information in the actual route, I use a custom (ie. "version") parameter in Accept header. I also set the version per mime type as in the below example. If version number is not set by the client or if the requested version does not exist this will fall back to default controller.
Create a class and inherit from DefaultHttpControllerSelector so you can fallback to base class behavior when you wanted to.
Override SelectController method as such:
public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
{
IDictionary controllers = GetControllerMapping();
IHttpRouteData routeData = request.GetRouteData();
string controllerName = (string)routeData.Values["controller"];
HttpControllerDescriptor controllerDescriptor;
if (string.IsNullOrWhiteSpace(controllerName))
{
return base.SelectController(request);
}
if (!controllers.TryGetValue(controllerName, out controllerDescriptor))
{
return null;
}
string version = GetVersionFromAcceptHeader(request);
if (string.Equals(version, "1"))
{
return controllerDescriptor;
}
string newName = string.Concat(controllerName, "V", version);
HttpControllerDescriptor versionedControllerDescriptor;
if (controllers.TryGetValue(newName, out versionedControllerDescriptor))
{
return versionedControllerDescriptor;
}
return controllerDescriptor;
}
Register this controller selector in your webapiconfig Register method:
config.Services.Replace(typeof(IHttpControllerSelector), new YourControllerSelector(config));

using filters with autofac in webapi2

I have a actionfilter something as below.. The filter basically adds a few attributes to the header of the response..
public class myHeaderAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext.Response != null)
//my code goes here
base.OnActionExecuted(actionExecutedContext);
}
}
I would normally call this in WebApiConfig.Register as config.Filters.Add(new myHeaderAttribute());
I wish to use Autofac in my project..
There is a page in autofac site (http://docs.autofac.org/en/latest/integration/webapi.html)which speaks of implementing IAutofacActionFilter.
But, I'm not very clear as to what I'm supposed to do.
I can create another class which implements IAutofacActionFilter and add the onActionExecuted method.
But do I also keep my present class or remove it along with the line in WebApiConfig.Register.
Also the page speaks of registering the Autofac filter provider as well as the class which implements IAutofacActionFilter. But no complete example exists.
Also, it speaks of using 'service location' in case we need per-request or instance-per-dependency services in our filters.
The whole thing seems a little too confusing to me. I would sincerely appreciate if someone who understands these concepts and has used Autofac in a web api2 project could guide me.
Thanks
Remove it. It explains exactly in the docs you reference yourself that it uses its own action filter resolver. See section "Provide filters via dependency injection".
Update
First register the filter provider:
var builder = new ContainerBuilder();
builder.RegisterWebApiFilterProvider(config);
Then register your actionfilter like so:
builder.Register(c => new myHeaderAttribute())
.AsWebApiActionFilterFor<YourController>(c => c.YourMethod(default(int)))
.InstancePerApiRequest();
So complete code:
var builder = new ContainerBuilder();
builder.RegisterWebApiFilterProvider(config);
builder.Register(c => new myHeaderAttribute())
.AsWebApiActionFilterFor<YourController>(c => c.YourMethod(default(int)))
.InstancePerApiRequest();
It's all right there in the docs. If you have any specific question then you can ask seperately. But this is becoming to be too broad.

How to make Unity pass a constructor parameter based on Web API request?

I'm using Web API in a multi-tenant environnement. Each tenant has their own database with an identical structure. The tenant name is included in the URL as a sub-domain : http://{tenant}.mysite.com/api/doodad/action
I've written a message filter (DelegatingHandler) to pull out the tenant name and find the corresponding database. I'm currently stashing this value in the request parameters.
Pretty much every controller action needs access a DbContext pointing to this database. I'm not using a repository pattern. I've created a second constructor on my DbContext that accepts the database name.
I'm using Unity to inject an instance of the DbContext in the ApiController. How can I get Unity to call the second constructor on the DbContext passing in the value from the request parameter?
I haven't tried this yet, but I think it should work...
You could create an action filter that would add the HttpRequestMessage to the current hierarchical container and then register your custom DbContext type with an InjectionFactory to pull out the HttpRequestMessage and get the DB name.
Here's some untested code...
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]
public class RegisterHttpRequestActionAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var container = GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IUnityContainer)) as IUnityContainer;
container.RegisterInstance(actionContext.Request, new HierarchicalLifetimeManager());
}
}
and the configuration...
IUnityContainer rootContainer = new UnityContainer();
GlobalConfiguration.Configuration.DependencyResolver = new UnityHierarchicalDependencyResolver(rootContainer);
GlobalConfiguration.Configuration.Filters.Add(new RegisterHttpRequestActionAttribute());
rootContainer.RegisterType<MyDbContext>(new HierarchicalLifetimeManager(), new InjectionFactory(container =>
new MyDbContext(container.Resolve<HttpRequestMessage>().Properties["TenantDB"] as string)));
(FYI, I reference the Unity.AspNet.WebApi NuGet package to get the UnityHierarchicalDependencyResolver)

Performing Explicit Route Mapping based upon Web Api v2 Attributes

I'm upgrading a custom solution where I can dynamically register and unregister Web Api controllers to use the new attribute routing mechanism. However, it seems to recent update to RTM break my solution.
My solution exposes a couple of Web Api controllers for administration purposes. These are registered using the new HttpConfigurationExtensions.MapHttpAttributeRoutes method call.
The solution also allows Web Api controllers to be hosted in third-party assemblies and registered dynamically. At this stage, calling HttpConfigurationExtensions.MapHttAttributeRoutes a second time once the third-party controller is loaded would raise an exception. Therefore, my solution uses reflection to inspect the RoutePrefix and Route attributes and register corresponding routes on the HttpConfiguration object.
Unfortunately, calling the Web Api results in the following error:
"No HTTP resource was found that matches the request URI".
Here is a simple controller that I want to use:
[RoutePrefix("api/ze")]
public sealed class ZeController : ApiController
{
[HttpGet]
[Route("one")]
public string GetOne()
{
return "One";
}
[HttpGet]
[Route("two")]
public string GetTwo()
{
return "Two";
}
[HttpPost]
[Route("one")]
public string SetOne(string value)
{
return String.Empty;
}
}
Here is the first solution I tried:
configuration.Routes.MapHttpRoute("ZeApi", "api/ze/{action}");
Here is the second solution I tried:
var type = typeof(ZeController);
var routeMembers = type.GetMethods().Where(m => m.IsPublic);
foreach (MethodInfo method in routeMembers)
{
var routeAttribute = method.GetCustomAttributes(false).OfType<RouteAttribute>().FirstOrDefault();
if (routeAttribute != null)
{
string controllerName = type.Name.Substring(0, type.Name.LastIndexOf("Controller"));
string routeTemplate = string.Join("/", "api/Ze", routeAttribute.Template);
configuration.Routes.MapHttpRoute(method.Name, routeTemplate);
}
}
I also have tried a third solution, whereby I create custom classes that implement IHttpRoute and trying to register them with the configuration to no avail.
Is it possible to use legacy-style route mapping based upon the information contained in the new routing attributes ?
Update
I have installed my controller in a Web Application in order to troubleshoot the routing selection process with the Web Api Route Debugger. Here is the result of the screenshot:
As you can see, the correct action seems to be selected, but I still get a 404 error.
Update2
After further analysis, and per Kiran Challa's comment below, it seems that the design of Web Api prevents mixing attribute routing and conventional routing, and that what I want to do is not possible using this approach.
I have created a custom attribute [RouteEx] that serves the same purpose of the Web Api [Route] attribute, and now my code works perfectly.
I guess, since this is not possible using the conventional attribute routing, none of the answers on this question could legitimately be consisered valid. So I'm not nominating an answer just yet.
You shouldn't be required to use reflection and inspect the attribute-routing based attributes yourself. Attribute routing uses existing Web API features to get list of controllers to scan through.
Question: Before the switch to attribute routing, how were you loading these assemblies having the
controllers?
If you were doing this by IAssembliesResolver service, then this solution should work even with attribute routing and you should not be needing to do anything extra.
Regarding your Update: are you calling MapHttpAttributeRoutes?