Reputation: 13
I'm building an asp.Net MVC application with Code First EntityFramework. I'm using Dependency Injection with Unity Container.
I have a context class like this
public partial class MyContext : DbContext
{
public MyContext()
: base("name=MyConnString")
{
Database.SetInitializer<MyContext>(null);
}
}
A Repository class like this:
public class Repository
{
public Repository(DbContext dataContext)
{
}
}
In Bootstrapper class I have this:
container.RegisterType<DbContext, MyContext>("DbContext",new HierarchicalLifetimeManager());
When I run the application, it throw this Exception:
The current type, System.Data.Common.DbConnection, is an abstract class > and cannot be constructed. Are you missing a type mapping?
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The current type, System.Data.Common.DbConnection, is an abstract class and cannot be constructed. Are you missing a type mapping?
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. The current type, System.Data.Common.DbConnection, is an abstract class and cannot be constructed. Are you missing a type mapping?
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The current type, System.Data.Common.DbConnection, is an abstract class and cannot be constructed. Are you missing a type mapping?
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
After research I found that this error is because Unity uses the most verbose constructor by default.
I need use the second constructor, but I don't know how configure Unity
Have you any idea?
Upvotes: 0
Views: 987
Reputation: 136094
You're looking for InjectionConstructor
:
public partial class MyContext : DbContext
{
[InjectionConstructor]
public MyContext()
: base("name=MyConnString")
{
Database.SetInitializer<MyContext>(null);
}
}
You may also find this useful reading: https://msdn.microsoft.com/en-us/library/ff650802.aspx
Upvotes: 1