Reputation: 391
I have a DI container and I want to pass in arguments to the constructor, via the DI container.
ie,
public interface IPerson { }
public class Person : IPerson {
private int _personId;
Person() { _personId = 0; }
Person(int id) { _personId = id; }
}
...
Container.Register(Component.For<IPerson>().ImplementedBy<Person>().Lifestyle.Transient);
...
//Person is already available
Container.Resolve<Person>(55);
//Person is not available
Container.Resolve<Person>();
This is basically what I want to do. Sometimes I need a new class created, sometimes I already have the class available. How would I achieve this please?
I have thought that I might be able to use dynamic parameters, but I am not sure how.
Thank you in advance.
A Factory pattern would make the solution elegant, however, this adds a bunch of complexity to my application, when all that is needed is a very simple solution which will work just as well.
Passing in a single integer in myself is far far easier than writing a whole factory to do the same job.
Upvotes: 2
Views: 2844
Reputation: 1673
this is my example how to pass params to constructor (DI contailer is unity):
static void Main(string[] args)
{
IUnityContainer container = new UnityContainer();
container.RegisterType<ILogger, FileLogger>(new InjectionConstructor(new[] { "c:\\myLog.txt" }));
ILogger logger = container.Resolve<FileLogger>();
logger.Write("My message");
Console.ReadLine();
}
According "Sometimes I need a new class created, sometimes I already have the class available. How would I achieve this please?" - try to implement Factory Pattern
Upvotes: 1
Reputation: 34349
You can pass an anonymous type to the Resolve
method which specifies the parameter values to use:
container.Resolve<IPerson>(new { id = 5 });
However, if you creating instances of Person
at various points in your application, then you don't want to be referencing the container, so you should use a PersonFactory
instead which resolves via the container. Have a look at the Typed Factory Facility.
Upvotes: 7