Reputation: 3039
I have chosen Castle.Windsor as IoC container for my app. This is my first IoC expirience so I need an advice configuring it.
The root class of the app is Scheduler
. It plans and performs different kinds of "jobs". Each job implements IWorker
interface, so I decided to inject a List<IWorker>
into Scheduler
. There will be many kind of "jobs" later, now there are two: Cleaner
and Writer
. Scheduler
needs single instance of Cleaner
, so default Singleton Lifestyle is OK. But I also need to inject number of Writer
s depends on count of XML files in some folder. What is optimal pattern to achieve this in my case?
Configuring container:
var container = new WindsorContainer();
// For IList injecting
container.Kernel.Resolver.AddSubResolver(new ListResolver(container.Kernel, true));
// Registering Scheduler
container.Register(CastleRegistration.Component.For<IScheduler>().ImplementedBy<Scheduler>);
// Registering Workers
container.Register(CastleRegistration.Component.For<IWorker>().ImplementedBy<Writer>());
container.Register(CastleRegistration.Component.For<IWorker>().ImplementedBy<Writer>());
// ... there are multiple Writers depends on XML files count
container.Register(CastleRegistration.Component.For<IWorker>().ImplementedBy<Cleaner>());
// Resolving
var sched = container.Resolve<IScheduler>();
Scheduler:
public class Scheduler : IScheduler
{
public IList<IWorker> Workers { get; set; }
public Scheduler(IList<IWorker> workers)
{
Workers = workers;
}
}
Writer:
public class Writer : IWorker
{
public string Source { get; set; }
public Writer()
{
}
public Writer(string source)
{
Source = source;
}
}
Cleaner:
public class Cleaner : IWorker
{
public Cleaner()
{
}
}
UPDATE:
I need to pass a parameter object (deserialized from XML) in each of Parser
s.
Should I just use foreach
loop in container configuration? Can Windsor's Typed factory help here? I need some guideline.
Upvotes: 2
Views: 1310
Reputation: 32954
basically what you want to do is something along these lines:
public class WriterFactory : IWriterFactory
{
public Writer Create(string fileName)
{
return new Writer(fileName);
//if your writers have other dependencies then inject those into the factory via the constructor and use them here
}
}
then register this factory
container.Register(CastleRegistration.Component.For<IWriterFactory>().ImplementedBy<WriterFactory>());
Then anywhere you need to create a writer take a dependency on the IWriterFactory
in the constructor
Upvotes: 1