在解析实例时如何指示 Unity 使用特定的构造函数

How can I indicate Unity use a specific constructor when resolves an instance

我正在使用 Code First EntityFramework 构建一个 asp.Net MVC 应用程序。我在 Unity 容器中使用依赖注入。

我有这样的上下文class

public partial class MyContext : DbContext
{
    public MyContext()
        : base("name=MyConnString")
    {
        Database.SetInitializer<MyContext>(null);
    }
}

像这样的存储库 class:

public class Repository
{
    public Repository(DbContext dataContext)
    {

    }
}

在 Bootstrapper 中 class 我有这个:

container.RegisterType<DbContext, MyContext>("DbContext",new HierarchicalLifetimeManager());

当我 运行 应用程序时,它抛出这个异常:

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?

来源错误:

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?

来源错误:

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.

经过研究我发现这个错误是因为Unity默认使用了最冗长的构造函数。

我需要使用第二个构造函数,但我不知道如何配置Unity

你有什么想法吗?

您正在寻找 InjectionConstructor:

public partial class MyContext : DbContext
{
    [InjectionConstructor]
    public MyContext()
        : base("name=MyConnString")
    {
        Database.SetInitializer<MyContext>(null);
    }
}

您可能还会发现这篇有用的文章:https://msdn.microsoft.com/en-us/library/ff650802.aspx