2013-04-15 62 views
20

當我嘗試使用XML配置我收到以下錯誤設置的參數:無構造函數的發現「Autofac.Core.Activators.Reflection.DefaultConstructorFinder」

None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'LM.AM.Core.Services.EmailService' can be invoked with the available services and parameters: Cannot resolve parameter 'System.String testSmtp' of constructor 'Void .ctor(System.String)'.

下面是相關的文件:

的web.config

<configSections> 
    <section name="autofac" type="Autofac.Configuration.SectionHandler, Autofac.Configuration" /> 
    </configSections> 

    <autofac> 
    <components> 
     <component type="LM.AM.Core.Services.EmailService , LM.AM.Core" service="LM.AM.Core.Infrastructure.Services.IEmailService , LM.AM.Core.Infrastructure"> 
     <parameters> 
      <parameter name="testSmtp" value="abc" /> 
     </parameters> 
     </component> 
    </components> 
    </autofac> 

服務類

public class EmailService : IEmailService 
{ 
    public string _testSmtp; 

    public EmailService (string testSmtp) 
    { 
     _testSmtp = testSmtp; 
    } 
} 

註冊

builder.RegisterType<EmailService>().As<IEmailService>().SingleInstance(); 

的Global.asax

var builder = new ContainerBuilder(); 
builder.RegisterModule(new ConfigurationSettingsReader("autofac")); 

builder.RegisterModule<Core.ModuleInstaller>(); 

builder.RegisterControllers(typeof(MvcApplication).Assembly); 
AutofacContainer.Container = builder.Build(); 

var emailSvc = AutofacContainer.Container.Resolve<IEmailService>(); 

我檢查容器知道XML參數的,我已經跟着維基接近盡我所能,但由於某些原因,該參數不解決唯一的構造函數,我收到上面的呃ROR。

這應該是非常簡單的。任何人都可以提供一些建議,我 可以嘗試讓這個工作?

回答

16

您已經註冊了兩次您的EmailService

一旦在web.config,一旦與

builder.RegisterType<EmailService>().As<IEmailService>().SingleInstance(); 

如果你有以上的Core.ModuleInstaller然後它將覆蓋web.config配置行。因爲在這裏你沒有指定參數Autofac拋出異常。

所以要解決這個問題只需從Core.ModuleInstaller模塊中刪除EmailService註冊

如果使用Core.ModuleInstaller多個地方,你需要有EmailService註冊有那麼你需要改變模塊的加載順序:

var builder = new ContainerBuilder(); 
builder.RegisterModule<Core.ModuleInstaller>(); 
builder.RegisterModule(new ConfigurationSettingsReader("autofac")); 

,或者告訴Autofac不重寫,如果的EmailService註冊它已經與PreserveExistingDefaults存在:

builder.RegisterType<EmailService>().As<IEmailService>() 
     .SingleInstance().PreserveExistingDefaults(); 
6

我創造了一個構造函數那裏之前有沒有,並使其私人,因此有defaul t構造函數,所以我得到了這個錯誤。必須公開我的構造函數。

+2

哦,上帝,你救了我的命! – Cleiton

相關問題