Reputation: 1416
I'm new to autofac, so sorry if i'm asking a dumb question.
I'm having trouble passing an argument to a constructor
I've got the following Interface and class:
interface IMyService
{
string GetVersion();
}
class MyService : webService, IMyService
{
public MyService(string serverPath)
: base(serverPath){}
public string GetVersion() { return "1.0"; }
}
This is how i'm setting things up:
public static class AutofacManager
{
public static IContainer Container { get; set; }
public static void Configure()
{
var builder = new ContainerBuilder();
builder.RegisterType<string>();
builder.Register<MyService>((c, p) => new MyService(c.Resolve<string>(p))).As<IMyService>();
Container = builder.Build();
}
}
and i'm using the object like this:
var ws = Container.Resolve<IMyService>(Autofac.TypedParameter.From<string>(url));
var ver = ws.GetVersion();
The problem is that an empty string is passed to the constructor. I expected it to pass the url varialbe.
Help? Thanks
Upvotes: 1
Views: 674
Reputation: 8953
Ok first thing is you try to register the string type, which is not needed (you can remove that lineà.
You can modify your delegate to match the following:
builder.Register((c, p) =>
{
var url = p.Named<string>("url");
return new MyService(url);
}).As<IMyService>();
You add a named parameter so you can specify url at resolve time.
The As will make sure to register as interface (otherwise you register concrete class).
Then to Resolve your object:
string MyUrl = "";
var ws = Container.Resolve<IMyService>(new NamedParameter("url", MyUrl));
EDIT: Instead of having to resolve with url everytime, you can also allow to set url at register time, eg:
string MyUrl = "hello";
builder.RegisterType<MyService>().
WithParameter(new NamedParameter("serverPath",MyUrl)).As<IMyService>();
Then, you can resolve as:
var ws = Container.Resolve<IMyService>();
Upvotes: 1