我一直有在此一展身手了一會兒沒有運氣:(使用Autofac與實現中的IDependencyResolver MVC5
當我被卡住:
我有一個MVC5 Web應用程序和我使用Autofac作爲IoC容器 基本上我有一個依賴需要我通過構造函數 傳入一個參數,但由於我通過IDependencyResolver接口解決了Autofac問題,我不允許 插入直接參數
我試圖使用委託工廠,但IM仍然得到錯誤 我敢肯定,我必須做一些錯誤....
////////////////
//My Interface//
////////////////
public interface IConfiguration
{
string OwnerId { get; set; }
IDictionary<string, string> GetAllSettings();
string GetSettingByKey(string SettingsKey);
}
///////////////////
//My Concrete Obj//
///////////////////
public class Configuration : IConfiguration
{
public delegate Configuration Factory(string ownerId); //Added this based on what's on the Autofac Wiki - Delegate Factories
public string OwnerId { get; set; }
public Dictionary<string, string> AllSettings {get; set;}
public Configuration(string ownerId) {
//Some logic that requires ownerId
}
public IDictionary<string, string> GetAllSettings()
{
//Some other logic irrelevant for now
}
public string GetSettingByKey(string settingsKey)
{
//Some other logic irrelevant for now
}
}
///////////////////////////////////
//Registering Dependencies in MVC//
///////////////////////////////////
var builder = new ContainerBuilder();
builder.RegisterType<Configuration>().As<IConfiguration>();
//Some other configuration
var container = builder.Build();
//Set Dependency Resolver for MVC5
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
//////////////////////////////////////////////////////////
//Somewhere in my MVC App where I require IConfiguration//
//////////////////////////////////////////////////////////
var ownerId = GetOwnerId();
//Where I require Help
var config = DependencyResolver.Current.GetService<IConfiguration>(); //How do I pass in a parameter (ownerId) to my underlying autofac container?
//I Tried this but it didn't work
var configFactory = DependencyResolver.Current.GetService<Func<string,IConfiguration>>();
var config = configFactory.Invoke(ownerId);
我得到的YSOD去了解這樣
與類型「Common.Configuration」 Autofac.Core.Activators.Reflection.DefaultConstructorFinder'裏找到的構造函數都不能在可用的服務和參數來調用: 無法解析的構造函數的參數「System.String OWNERID」 'Void .ctor(System.String)'。
在此先感謝球員:)
我需要放置一個賞金這個夥計:)? – 2014-10-09 03:53:58
什麼是'ownerId'?是基於運行時條件(例如傳入請求或用戶會話)而改變的東西,還是在應用程序生命週期內(例如因爲它在配置文件中配置)而被修復的東西? – Steven 2014-10-09 06:29:11
嗨史蒂文謝謝你的問題是它的東西,這是在運行時間條件下確定:)我不能把它放在配置中,因爲它還不知道... – 2014-10-09 19:34:59