2016-04-28 46 views
1

我接收來自Autofac ;:Autofac無法解析的DbContext

沒有與類型「Autofac.Core.Activators.Reflection.DefaultConstructorFinder」中發現的構造的「MyService`1 [MyContext]」可以是此錯誤消息用可用的服務和參數調用: 無法解析構造函數'Void .ctor(MyContext)'的參數'MyContext context'。

錯誤發生在這行代碼(也顯示在下面的代碼):

IMyService myService = container.Resolve<IMyService>(); // error here 

我感興趣的是,當我包括我的登記這條線,一切正常:

builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource()); 

事實上,它在我註冊AnyConcreteType時都有效......讓我相信我沒有註冊某些東西。我的問題是我沒有註冊什麼?該錯誤消息似乎將MyContext命名爲罪魁禍首,但顯然我按照下面所示註冊它。
我真的不想使用AnyConcreteType ...全部捕捉,因爲我想顯示只註冊我需要的類。

我的服務就是構建這樣的:

public class MyService<T> : BaseService<T>, IMyService where T:DbContext,IMyContext 
{ 
    public MyService(T context) : base(context) 
    { 
    } 
} 

爲MyService從BaseService派生:

public abstract class BaseService<T> : IDisposable where T:DbContext, IMyContext 
{ 
    internal T db; 

    public BaseService(T context) 
    { 
     db = context; 
    } 
} 

MyContext傳遞爲了MyService和構造是這樣的:

public partial class MyContext : DbContext, IMyContext 
{ 
    public MyContext(INamedConnectionString conn) 
     : base(conn.ConnectionString) 
    { 
     Configuration.ProxyCreationEnabled = false; 
    } 
} 

這裏NamedConnectionString

public class NamedConnectionString : INamedConnectionString 
{ 
    public string ConnectionString { get; set; } 
} 

這裏是我註冊上面:

builder.RegisterType<MyService<MyContext>>().As<IMyService>(); 
builder.RegisterType<NamedConnectionString>().As<INamedConnectionString>().SingleInstance(); 
builder.RegisterType<MyContext>().As<IMyContext>().InstancePerLifetimeScope(); 
builder.RegisterType<DbContext>(); // is this necessary?? 

這裏是我怎麼稱呼它:

var container = builder.Build(); 
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); 
    INamedConnectionString namedConnectionString = container.Resolve<INamedConnectionString>(); 
    namedConnectionString.ConnectionString = myConnectionString; 
    IMyService myService = container.Resolve<IMyService>(); // error here 

回答

2

Autofac and ASP .Net MVC 4 Web API

以上線程相關。它沒有回答這個問題,但它幫助我開始正確的故障排除。該解決方案是在這裏:

我刪除了這兩條線:

builder.RegisterType<MyContext>().As<IMyContext>().InstancePerLifetimeScope(); 
builder.RegisterType<DbContext>(); // is this necessary?? 

,並用這個代替他們:

builder.RegisterType<MyContext>().InstancePerLifetimeScope(); 
0

這爲我工作

builder.RegisterType( 。)。如()InstancePerLifetimeScope();