1

I am facing an issue when I use Unity to inject a dependency with two partial classes. This is what I have done:

public partial class MyDbContext : IMyDbContext
{
    // code
}

public partial class MyDbContext : IMyDbContext
{
     // code
}

public interface IMyDbContext
{
    // code
}

var container = new UnityContainer();
container.RegisterType<IMyDbContext,      
MyDbContext>(new HierarchicalLifetimeManager());
config.DependencyResolver = new UnityResolver(container);

Using the above code, I get an exception about my db is null. But, If I remove one partial class, so I will have only one partial class, all works fine. I would very appreacite if you could you please on this.

EDIT: When I in debug mode, the Unit container GetService method catches an exception ResolutionFailedException.

2 Answers 2

1

I solved this issue by registering the instance and not the type. However, any other solutions are welcome.

var container = new UnityContainer();
MyDbContext context = new MyDbContext()
container.RegisterInstance<IMyDbContext>(context);
config.DependencyResolver = new UnityResolver(container);
Sign up to request clarification or add additional context in comments.

Comments

0

Remove one of the interfaces. One of the partial classes implements it so the other one can't. Remember that the partial class is compiled together in a single class so you can't have both partials implement the same interface because once combined, it is unknown which partial is actually implementing it.

1 Comment

Thank you for the response. If you mean to remove the interface from one partial class I already try it but still doesn't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.