We are currently working with a large solution that contains a WCF project (.NET Framework 4.7.2) along with multiple .NET Standard 2.0 libraries.
We're trying to register these libraries with Unity (DI). Loading the libraries in the container works fine. However resolving these classes in a constructor fails.
Unity.Exceptions.ResolutionFailedException: 'Resolution of the dependency
failed, type = 'PROJECTNAME.Service.ITypeDependentonDbContext', name = '(none)'.
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The current type,
PROJECTNAME.DAL.Repositories.Interfaces.IDbContext, is an interface
and cannot be constructed. Are you missing a type mapping?
More specifically, each library has a ModuleInit class where we register types on the ModuleRegistrar (for MEF2) like so:
public void Initialize(IModuleRegistrar registrar)
{
registrar.RegisterType<IDbContext, DbContext>();
// etc
}
Then, in our .NET Framework project, we register types to the Unity Container:
protected override void ConfigureContainer(IUnityContainer container)
{
container
.RegisterType<ISomeService, SomeService>()
.RegisterType<ITypeDependentonDbContext, TypeDependentonDbContext>();
//etc
ModuleLoader.LoadContainer(container, ".\\bin", "*.*.dll");
}
Finally, in a class in the .NET Framework project, we have
public class SomeService : ISomeService
{
private readonly ITypeDependentonDbContext _typeDependentonDbContext;
/// <summary>
/// constructor
/// </summary>
/// <param name="typeDependentonDbContext"></param>
public SomeService(ITypeDependentonDbContext typeDependentonDbContext)
{
_typeDependentonDbContext = typeDependentonDbContext ?? throw new ArgumentNullException(nameof(typeDependentonDbContext));
}
}
The weird thing is that the exception is not thrown if we register ALL types that we depend on directly in the container. This is in contrast to an existing .NET framework solution where we register each type in the moduleInit class of that project, exactly as presented here. However this doesn't seem to work with .NET standard 2.0 projects.
Additionally, while debugging it seems that the classes seem to be registered just fine in the container - each interface is mapped to the correct implementation class. Things only seem to go wrong when we actually wish to resolve the dependecy in a constructor.
Does anyone have any ideas as to why this may occur?