how to pass parameters on resolve time in autofac

妖精的绣舞 提交于 2020-06-14 06:29:43

问题


I write following register type in autofac:

 builder.RegisterType<NoteBookContext>()
        .As<DbContext>()
        .WithParameter(ResolvedParameter.ForNamed<DbContext>("connectionstring"));

In fact I write this code for injecting NoteBookContext with a connectionstring parameter. (ie : new NoteBookContext(string connectionstring))

Now , How can I Pass value of parameter at runtime?


回答1:


The WithParameter method has a overload that accept delegate for dynamic instanciation.

The first argument is a predicate selecting the parameter to set whereas the second is the argument value provider :

builder.RegisterType<NoteBookContext>()
       .As<DbContext>()
       .WithParameter((pi, c) => pi.Name == "connectionstring", 
                      (pi, c) => c.Resolve<IConnectionStringProvider>().ConnectionString);

See Passing Parameters to Register from Autofac documentation for more detail.




回答2:


In order to pass the connection string value while resolving, we first need to pass the delegate of the constructor into the Register method, and then pass the value of connection string with the NamedParameter into the Resolve method.

For example:

ContainerBuilder builder = new ContainerBuilder();

builder.Register((pi, c) => new NoteBookContext(pi.Named<string>("connectionstring")))
            .As<DbContext>();

Now, on resolve time, we can assign to the resolved DBContext the conncetionstring value of Consts.MyConnectionString:

IContainer container = builder.Build();

NoteBookContext noteBookContext = container.Resolve<DbContext>(
    new NamedParameter(
        "connectionstring", Consts.MyConnectionString
    )
);



回答3:


you dont need to do a lot/anything special if you are just passing in something quick, for me i was able to just pass in an instance of what i wanted to get injected.

container.Resolve<IFoo>(new List<Parameter>{ new TypedParameter(something.GetType(), something)});

Note: I know what i passed in was not registered with the container.



来源:https://stackoverflow.com/questions/36835865/how-to-pass-parameters-on-resolve-time-in-autofac

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!