Having problems with IoC #446
-
I've ran into some unexpected problems with Microsoft IoC extension. I thought resolver would provide the service to the command, but that wasn't the case.
suggests one of 3 things:
I looked for similar usages in examples and tests, but nothing really struck be as similar. My questions would be:
Relevant discussions: |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Ok, the code example was helpful and I understand why it's failing for you. We have not added support to resolve method parameters from the container. If we did, we might follow the pattern of ASP.NET and require the parameter to be attributed with [FromServices] (You could propose this as a feature and submit a PR if you'd like) CommandDotNet expects the command class to be created by the DI container and in that case, you'd inject the dependencies via constructor or property injection, depending on what you've enabled in the container. This way, the DI container owns the instance of the command class. In your example, Program is a command class since it defines commands. public class Program
{
static int Main(string[] args)
{
var services = new ServiceCollection();
services.AddSingleton<IMyService>(new MyService());
services.AddSingleton<Program>();
return new AppRunner<Program>()
.UseMicrosoftDependencyInjection(services.BuildServiceProvider())
.Run(args);
}
private IMyService _myService;
public Program(IMyService myService) => _myService = myService;
public void Test(
Arguments args,
IConsole consoleService)
{
consoleService.WriteLine(_myService.Foo(args.Arg1, args.Arg2));
}
} sidenote: in #437, he seems to have gotten the DI to work but there was a null ref in the Print method of his code. He no longer had errors from his container while resolving the property. |
Beta Was this translation helpful? Give feedback.
Ok, the code example was helpful and I understand why it's failing for you. We have not added support to resolve method parameters from the container. If we did, we might follow the pattern of ASP.NET and require the parameter to be attributed with [FromServices] (You could propose this as a feature and submit a PR if you'd like)
CommandDotNet expects the command class to be created by the DI container and in that case, you'd inject the dependencies via constructor or property injection, depending on what you've enabled in the container. This way, the DI container owns the instance of the command class. In your example, Program is a command class since it defines commands.