Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to debug when a dependency fails to instantiate?

How do you debug dependency injection (using Unity DI) when the dependancy does not instantiate?

eg Given a service class with dependencies:

public class FooService : IFooService
{
    [Dependency]
    public BarService BarService { get; set; }
    [Dependency]
    public AnotherService AnotherService { get; set; }

    // other code fails because BarService and AnotherService are null
}

And in Global.asax.cs

private void ConfigureIoC()
{
    container
        .ConfigureAutoRegistration()
        .LoadAssembliesFrom(assemblyPaths)
        .ExcludeSystemAssemblies()
        .Include(If.Any, Then.Register()) 
        .ApplyAutoRegistration();

    var serviceLocator = new UnityServiceLocator(container);
    ServiceLocator.SetLocatorProvider(() => serviceLocator);
}

The IFooService is also instantiated by Unity, but that uses constructor injection instead (and it works):

public class FooController : Controller
{
    private readonly IFooService _fooService;
    public FooController(IFooService fooService)
    {
        _fooService = fooService;
    }
}

How can I debug this to see why the dependencies are failing to instantiate. No exceptions are being thrown (or if they are then Elmah is not catching and logging them).

like image 918
JK. Avatar asked Dec 05 '25 11:12

JK.


1 Answers

The dependency is not injected because the DependencyAttribute is on the concrete class instead of the interface.

As DI attributes can be harmful I would recommend you change the registration to

container.RegisterType<IFooService,FooService>(new InjectionProperty("BarService"), new InjectionProperty("AnotherService"));

Resolving IFooService will then return an instance of FooService with the injected dependencies.

like image 148
Sebastian Weber Avatar answered Dec 07 '25 01:12

Sebastian Weber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!