我剛開始第一次使用依賴注入進行工作,我在ASP.NET MVC 2網站中用作Ninject 2.0作爲我的IoC容器,並且遇到激活錯誤我不知道如何應對。我相信這很簡單,所以希望有人能夠在沒有太多想法的情況下指引我走向正確的方向。ASP.NET MVC - Ninject 2.0激活錯誤
我在我的類BaseController上有一個屬性,它接受一個IWebsiteSettings並用[Inject]屬性標記。在我StandardKernel我加載模塊用以下代碼:
public class WebModule : Module
{
public override void Load()
{
Bind<IWebsiteSettings>()
.ToProvider(new WebsiteSettingsProvider(WebConfigurationManager.AppSettings))
.InSingletonScope();
}
}
public class WebsiteSettingsProvider : Provider<WebsiteSettings>
{
private const string WebsiteNameKey = "Website.Name";
private const string ContactFormEmailSubjectKey = "ContactForm.EmailSubject";
private const string ProductImageDirectoryKey = "Products.ImageDirectory";
private const string UploadTempDirectoryKey = "Uploads.TempDirectory";
protected NameValueCollection Settings { get; set; }
public WebsiteSettingsProvider(NameValueCollection settings)
{
Settings = settings;
}
protected override WebsiteSettings CreateInstance(IContext context)
{
return new WebsiteSettings
{
WebsiteName = Settings[WebsiteNameKey] ?? string.Empty,
ContactFormEmailSubject = Settings[ContactFormEmailSubjectKey] ?? string.Empty,
ProductImageDirectory = Settings[ProductImageDirectoryKey] ?? string.Empty,
UploadsTemporaryDirectory = Settings[UploadTempDirectoryKey] ?? string.Empty
};
}
}
這是相當straightforward-我試圖從web.config文件中加載一些數據,並將其存儲在一個單獨的對象爲在我的控制器使用。對Bind的調用似乎完全按照它應該的方式工作,並且我的提供程序中的Settings屬性正在使用配置文件中的AppSettings集合正確初始化。不過,當應用程序加載的第一次:
Server Error in '/' Application. Error activating SByte* using implicit self-binding of SByte* No constructor was available to create an instance of the implementation type. Activation path: 4) Injection of dependency SByte* into parameter value of constructor of type string 3) Injection of dependency string into property WebsiteName of type WebsiteSettings 2) Injection of dependency IWebsiteSettings into property WebsiteSettings of type HomeController 1) Request for HomeController Suggestions: 1) Ensure that the implementation type has a public constructor. 2) If you have implemented the Singleton pattern, use a binding with InSingletonScope() instead.
有趣的是,如果我刷新頁面,我不得到的異常,並Kernel.Get()的調用返回正確的對象。
有什麼建議?
什麼是irc頻道? – 2010-10-11 02:27:58