C#
C#

help

Root Question Message

PontiacGTX
PontiacGTX10/28/2022
Cannot resolve constructor for String type. Using Unity container

I am sending a string to StringCon Class but it doesnt resolve when injecting into HomeController... here is the code

var con = ConfigurationManager.AppSettings["MyConnectionString"];
            var paramStringCon = new ParameterOverrides();
            container.RegisterType<StringCon>();
            container.Resolve<StringCon>(new ResolverOverride[]
            {
                new ParameterOverride("str", con)
            });
            
            var logProd = container.Resolve(typeof(Microsoft.Extensions.Logging.ILogger<ProductoRepository>));

                container.RegisterType<ProductoRepository>(nameof(ProductoRepository),
                new InjectionConstructor(container.Resolve<StringCon>(new ResolverOverride[]
            {
                new ParameterOverride("str", con)
            }), logProd));
             new UnityDependencyResolver(container);
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
Yawnder
Yawnder10/28/2022
Are you just like... writing anything you can think of?
Your registrations should happen very early in the process normally, and you should seldom use overrides. Use named registrations instead.
icebear
icebear10/28/2022
i'd wrap the string in a options-class, register and configure it in the ServiceCollection and let DI inject it into constructors as needed
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-6.0
PontiacGTX
PontiacGTX10/28/2022
it is what I have done if you see container.RegisterType<StringCon>();
icebear
icebear10/28/2022
sry somehow completely missed it's about unity ^^
but i'm with yawnder ... why are you trying to override the parameter when resolving, instead of registering it with the right value?
you seem to use the same value in all places, right?
phaseshift
phaseshift10/28/2022
that isn't 'IOptions' type/pattern that was being referenced by icebear
PontiacGTX
PontiacGTX10/28/2022
technically yes but no
PontiacGTX
PontiacGTX10/28/2022
I think that is more of an automatic thing in ASP.NET Core
PontiacGTX
PontiacGTX10/28/2022
I fixed it had to instance from a factory
PontiacGTX
PontiacGTX10/28/2022
container.RegisterFactory(typeof(StringCon),instance=>new StringCon(con), FactoryLifetime.Scoped);
phaseshift
phaseshift10/28/2022
your string comes from config
PontiacGTX
PontiacGTX10/28/2022
yeah i read it from the Config
phaseshift
phaseshift10/28/2022
so you can just use IOptions instead of hard wiring all these overridees
PontiacGTX
PontiacGTX10/28/2022
ASP.NET has IOptions?
PontiacGTX
PontiacGTX10/28/2022
it isnt asp.net core
phaseshift
phaseshift10/28/2022
i dont think ioptions is new
PontiacGTX
PontiacGTX10/28/2022
so yeah I have to manually bind the properties
ContactFrequently Asked QuestionsJoin The DiscordBugs & Feature RequestsTerms & Privacy