1
votes

I recently create a sample application with Web API template. I also Installed the Microsoft Unity Mvc package and add a test service as following:

public interface IUtilityService
{
    string GetToken(int length);
}

public class UtilityService : IUtilityService
{
    public string GetToken(int length)
    {
        return "ABC";
    }
}

The UnityConfig and UnityWebActivator are just created by installing the package and I just registered my own service in it as following:

public static class UnityWebActivator
{
    /// <summary>Integrates Unity when the application starts.</summary>
    public static void Start() 
    {
        var container = UnityConfig.GetConfiguredContainer();

        FilterProviders.Providers.Remove(
            FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
        FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));

        DependencyResolver.SetResolver(new UnityDependencyResolver(container));

        // TODO: Uncomment if you want to use PerRequestLifetimeManager
        // Microsoft.Web.Infrastructure.DynamicModuleHelper
        //  .DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
    }

    /// <summary>Disposes the Unity container when the application is shut down.</summary>
    public static void Shutdown()
    {
        var container = UnityConfig.GetConfiguredContainer();
        container.Dispose();
    }

And the UnityConfig:

public class UnityConfig
{
    #region Unity Container
    private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
    {
        var container = new UnityContainer();
        RegisterTypes(container);
        return container;
    });

    public static IUnityContainer GetConfiguredContainer()
    {
        return container.Value;
    }
    #endregion

    public static void RegisterTypes(IUnityContainer container)
    {
        // NOTE: To load from web.config uncomment the line below. Make sure to 
        // add a Microsoft.Practices.Unity.Configuration to the using statements.
        // container.LoadConfiguration();

        // TODO: Register your types here
        container.RegisterType<IUtilityService, UtilityService>();
    }
}

Microsoft Unity resolve my service in the Home controller once I run the test application, However, It can not resolve the service once I want to call a method inside Values controller from the JQuery.

The code are as follow:

private readonly IUtilityService utilityService;

public HomeController(IUtilityService utilityService)
{
    this.utilityService = utilityService;
}

public ActionResult Index()
{
    ViewBag.Title = utilityService.GetToken(10);

    return View();
}

And the Values Controller is as follow:

private readonly IUtilityService utilityService;

public ValuesController(IUtilityService utilityService)
{
    this.utilityService = utilityService;
}

// GET api/values
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

This is also the jquery code I call the Values controller:

 $(document).ready(function () {
    console.log("ready!");

    $('#call').click(function () {
        $.ajax({
            type: "GET",
            dataType: 'json',
            url: "api/Values",
            success: function (response) {
                console.log("success!");
            },
            error: function (response, textStatus, errorThrown) {
                console.log("error!");
            }
        });
    })
});

One I click the button to run the ajax call to the values controller I get the error below and seems the controller can not be initiated because of not having parameter less constructor.

Error:

An error occurred when trying to create a controller of type 'ValuesController'. Make sure that the controller has a parameterless public constructor.

1
Have you added the unity container to the HttpConfiguration.DependencyResolver in the WebApiConfig.cs?Marcus Höglund
I think this line of code in the UnityWebActivator class shoud be enough. DependencyResolver.SetResolver(new UnityDependencyResolver(container));ali

1 Answers

1
votes

That is a common unhelpful error message that usually indicates that the framework cannot resolve the dependencies of the controller when initializing it.

In this case you need to set the DependencyResolver for Web API. Both MVC and Web API have dependency resolvers but they belong to differing namespaces. As already mentioned in the comments you need to set the dependency resolver of the HttpConfiguration when the configuring the Web API.

public static class WebApiConfig {

    public static void Register(HttpConfiguration config) {

        var container = UnityConfig.GetConfiguredContainer();

        //...any other settings to be applied to container.

        config.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);

        //...other code removed for brevity
    }
}