Search code examples
c#ninjectautofac

c# convert ninject specific bindings to autofac


I have two problems on converting bindings from ninject to autofac.

The first is:

Bind<IMapper>().ToConstant(new Container().Mapper);

and the second is:

Bind<Context>().ToSelf()
               .WithConstructorArgument(CONNECTION_STRING, 
               c => c.Kernel.Get<IUserDatabase>().ConnectionString)

May you lend me a hand?

Thank you


Solution

  • For the first one:

    builder
        .RegisterInstance(new Container().Mapper)
        .As<IMapper>();
    

    For the second one:

    // First option, with a parameter
    builder
        .RegisterType<Context>()
        .AsSelf()
        .WithParameter(
            (parameter, context) => parameter.Name == CONNECTION_STRING,
            (parameter, context) => context.Resolve<IUserDatabase>().ConnectionString));
    
    // Second option, with a lambda
    builder
        .Register(x => new Context(x.Resolve<IUserDatabase>().ConnectionString))
        .AsSelf();
    

    I prefer the second option as you get static checks on the constructor of your Context class, but it can be a pain to maintain if you have lots of parameters.

    I'd suggest reading the article linked from this tweet. It talks about how using primitives as constructor parameters makes our lives harder and how to work around it.