Just used DI containers in MVC projects, via constructor injection, and I'd need to now inject a service into a console app. I'm using Autofac so I followed what I found here.
The code would be something like this:
The service the console app depends on:
public interface IBatchService
{
void WriteInformation(string input);
}
public class BatchService : IBatchService
{
public void WriteInformation(string input)
{
Console.WriteLine(input);
Console.ReadKey();
}
}
The console app main method
public class Program
{
private static IContainer Container { get; set; }
static void Main(string[] args)
{
var builder = new ContainerBuilder();
builder.RegisterType<BatchService.BatchService>().As<IBatchService>();
Container = builder.Build();
using (var scope = Container.BeginLifetimeScope())
{
var batchService = scope.Resolve<IBatchService>();
batchService.WriteInformation("Injected!");
}
}
It's using the Service Locator if I'm not wrong (I'm trying to get my head around all of this), which I would be likely to avoid in case I could as it's thoroughly discussed in the web. But can I actually avoid it in a console app? Can any see any big flaw with this implementation?
The main method is almost as simple as this one, only one call to one service (although the service doesn't write a console). And that's the only code in the project in fact.