Answered by:
Unity Dependency Resolver not working with my Web Api

Question
-
User1642115476 posted
Hello,I just created a web API and I'm using Unity as my dependency injection resolver. It's not working.
I had it working at one point, then it stopped working, then it started working again (not sure what I did), and now it's not working again. The exact nature of the problem is not consistent, but the most common error I've been getting is:
"Resolution of the dependency failed, type = "System.Web.Http.Dispatcher.IHttpControllerActivator", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The current type, System.Web.Http.Dispatcher.IHttpControllerActivator, is an interface and cannot be constructed. Are you missing a type mapping?
-----------------------------------------------
At the time of the exception, the container was:Resolving System.Web.Http.Dispatcher.IHttpControllerActivator,(none)
The current type, System.Web.Http.Dispatcher.IHttpControllerActivator, is an interface and cannot be constructed. Are you missing a type mapping?"
Here is my controller which requires injection:
public class FileUploadController : ApiController
{
private readonly IPromComService _promComService;public FileUploadController(IPromComService promComService)
{
_promComService = promComService;
}// Borrowed from: http://www.asp.net/web-api/overview/advanced/sending-html-form-data-part-2
public async Task<HttpResponseMessage> PostUploadFile()
{
//... uploads a file and saves it to a folder
}}
}Here is Startup.cs:
[assembly: OwinStartup(typeof(WebAPI.App_Start.Startup))]
namespace WebAPI.App_Start
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureOAuth(app);
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); // GGG - Allow CORS for ASP.NET Wen API. <-- I think this means allow access to external sources.
app.UseWebApi(config);
}// GGG - This is where authentication tokens will be issued:
public void ConfigureOAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new SimpleAuthorizationServerProvider()
};// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
}Here is WebApiConfig.cs:
namespace WebAPI.App_Start
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services// Web API routes
config.MapHttpAttributeRoutes();config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);// GGG - For formatting JSON stuff:
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();// For dependency injection into the controller constructors:
var container = new UnityContainer();
container.RegisterType<IPromComService, PromComService>(new HierarchicalLifetimeManager());
config.DependencyResolver = new UnityResolver(container);
}
}
}and finally, here is UnityResolver.cs:
namespace WebAPI
{
public class UnityResolver : IDependencyResolver
{
protected IUnityContainer container;public UnityResolver(IUnityContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
this.container = container;
}public object GetService(Type serviceType)
{
try
{
return container.Resolve(serviceType);
}
catch (ResolutionFailedException e)
{
return null;
}
}public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return container.ResolveAll(serviceType);
}
catch (ResolutionFailedException e)
{
return new List<object>();
}
}public IDependencyScope BeginScope()
{
var child = container.CreateChildContainer();
return new UnityResolver(child);
}public void Dispose()
{
container.Dispose();
}
}
}Does anyone know what the problem is?
Thursday, September 22, 2016 8:56 PM
Answers
-
User36583972 posted
Hi gib9898_00,
From your error message, It is difficult to identify the cause. So, I suggest you can refer the following tutorials/example and make a sample on your side.
Dependency Injection for Web API Controllers:
https://code.msdn.microsoft.com/ASP-NET-Web-API-Tutorial-468ee148
Dependency Injection in ASP.NET Web API 2:
http://www.asp.net/web-api/overview/advanced/dependency-injection
Best Regards,
Yohann Lu
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Friday, September 23, 2016 4:12 AM