Search code examples
c#.netdependency-injectionsimple-injector

Create a concrete implementation and then register it


Fist of all , I use the simpleInjector.

private static readonly Container Container = new Container();

I have

public interface ILine
{
    Guid LineId { get; set; }

    void Run();
}

And

public class CallFlowApplication : ICallFlowApplication
{
    private ILine _lineApi;
    public CallFlowApplication(ILine line)
    {
        _lineApi = line;
    }

    public void HandleCall()
    {
        throw new NotImplementedException();
    }
}

Now also:

static void RegisterDependencies()
    {
        VoiceElementsCallFlowService.Container = Container;
        Container.Register<ICallFlowService, VoiceElementsCallFlowService>();

        Container.Register<ICallFlowApplication, CallFlowApplication>();

        // TODO: Register your application here
        Container.Register<IApplicationFactory>(() => new ApplicationFactory
                {
                    { 1, () => Container.GetInstance<CallFlowApplication>() }
                }, Lifestyle.Singleton);
    }

When I play the application, I got the error at the code Container.Verify();

The configuration is invalid. Creating the instance for type ICallFlowApplication failed. The constructor of type CallFlowApplication contains the parameter with name 'line' and type ILine that is not registered. Please ensure ILine is registered, or change the constructor of CallFlowApplication.

My question is that I am not sure how to deal with ILine here.


Solution

  • Register ILine with your concrete implementation you have for ILine, VoiceElementsLine:

    Container.Register<ILine, VoiceElementsLine>();
    Container.Register<ICallFlowApplication, CallFlowApplication>();
    

    When the container is attempting to instantiate CallFlowApplication, the constructor for that takes an ILine but you haven't registered an ILine so it doesn't have anything to give it which is why it fails. You need to tell the container "hey, when something asks for an ILine give it a VoiceElementsLine."