z4kn4fein / stashbox

A lightweight, fast, and portable dependency injection framework for .NET-based solutions.

Home Page:https://z4kn4fein.github.io/stashbox

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

resolving with custom parameter values

bonesoul opened this issue · comments

I've a named registration of;

_container.Register<IVariantSubproduct, StainlessSteelPlate>("PAS.LEV");

and definition of the class is

        public StainlessSteelPlate(ISubproduct subproduct):base(subproduct)
        { }

So i can named-resolve it like;

return _resolver.Resolve<IVariantSubproduct>(code);

but how can I supply the value of parameter?

return _resolver.Resolve<IVariantSubproduct>(code, params?);

I tried changing my factory resolver to;

        public IVariantSubproduct GetVariantSubproduct(string code, ISubproduct subproduct)
        {
            return _resolver.Resolve<IVariantSubproduct>(code, false, new object[] {subproduct});
        }

and calling it with;

_subproductFactory.GetVariantSubproduct(x.Code, x);

but getting

Cannot resolve type WareEngine.Modules.Stocks.Models.Subproducts.Variant.IVariantSubproduct.
Service is not registered or unresolvable type requested

Hey, the second one is the proper way to pass a parameter, however, it's not working now because of a bug. I'm going to fix it now and publish a new version.
Thanks for reporting!

Could you please check the latest pre-release version? Thanks!

Okay i'll let you know.

meanwhile i used this workaround

return _resolver.ResolveFactory<ISubproduct, IVariantSubproduct>(subproduct.Code)(subproduct);

okay
return _resolver.Resolve<IVariantSubproduct>(code, false, new object[] {subproduct});

works all good now but I guess I've found a better way to accomplish what i need;

return _resolver.ResolveFactory<ISubproduct, IVariantSubproduct>(subproduct.Code)(subproduct);

Thanks for the feedback!
Sure, that works too, but I would recommend saving the generated factory somewhere because although it's cached by the container, it could be recreated when the dependency tree changes.

so when it get's recreated will i have problems accessing the items or your recommendation is just sake of optimization?

Just for optimization purposes, the factory remains stable. The container wipes out the whole cache only when you register something after you created the factory and if you do that frequently it could be regenerated over and over again, but if it's not the case, it'll remain cached, so it's fine with your version as well.

Ah I do registrations only while initial initializing, still thanks for the heads up and great library!