I am trying to implement the dependency injection in ASP.Net web API with unity container and have implemented the exactly with below 2 articles:

  1. https://stackoverflow.com/a/38770689/3698716
  2. https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/dependency-injection

Both are related to each other with some minor change but implementation for both are same.

After implementing my code is breaking at return _container.Resolve(serviceType); with stackoverflow exception in the GetService method of the UnityResolver.cs class, below is the exception I am getting:

System.StackOverflowException: 'Exception of type 'System.StackOverflowException' was thrown.'

Is there any idea about that?

My UnityConfig.cs

 public static class UnityConfig
    {
        public static UnityContainer Config()
        {
            UnityContainer container = new UnityContainer();

            container.RegisterType<IProduct, ProductBLL>();

            return container;
        }
    }

My WebApiConfig.cs

 public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        var container = UnityConfig.Config();
        config.DependencyResolver = new UnityResolver(container);
        
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

And My UnityResolver.cs

public class UnityResolver : IDependencyResolver
{
    private readonly IUnityContainer _container;

    public UnityResolver(IUnityContainer container)
    {
        _container = container;
    }

    public object GetService(Type serviceType)
    {
        try
        {
            return _container.Resolve(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return null;
        }
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return _container.ResolveAll(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return new List<object>();
        }
    }

    public IDependencyScope BeginScope()
    {
        var child = _container.CreateChildContainer();
        return new UnityResolver(child);
    }

    public void Dispose()
    {
        _container.Dispose();
    }
}

And My PracticeController.cs

public class PracticeController : ApiController
{
    private IProduct objProduct;

    public PracticeController(IProduct product)
    {
        this.objProduct = product;
    }

    [HttpGet]
    public string TestPractice()
    {

        string val = objProduct.InsertData();

        Console.WriteLine(val);
        Console.ReadLine();

        return val;
    }
}
0

There are 0 answers