I've been having a go at this for a while no luck :(
Where I'm getting stuck:
I have an MVC5 web application and I'm using Autofac for the IoC container under the hood. Basically I have a dependency that requires me to pass in a parameter through the constructor but since I'm resolving Autofac through the IDependencyResolver interface I'm not allowed to insert parameters directly.
I've tried to use a delegate factory but im still getting errors I'm sure I must be doing something wrong....
////////////////
//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);
The YSOD I'm getting goes about like this
None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'Common.Configuration' can be invoked with the available services and parameters: Cannot resolve parameter 'System.String ownerId' of constructor 'Void .ctor(System.String)'.
Thanks in advance guys :)
ownerId? Is that something that changes based on runtime conditions (such as the incoming request or the user session) or is it something that is fixed for the duration of the lifetime your application (for instance because it is configured in the configuration file)?