z4kn4fein / stashbox

A lightweight, fast, and portable dependency injection framework for .NET-based solutions.
https://z4kn4fein.github.io/stashbox
MIT License
141 stars 10 forks source link

resolving with custom parameter values #91

Closed bonesoul closed 4 years ago

bonesoul commented 4 years ago

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?);

bonesoul commented 4 years ago

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
z4kn4fein commented 4 years ago

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!

z4kn4fein commented 4 years ago

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

bonesoul commented 4 years ago

Okay i'll let you know.

meanwhile i used this workaround

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

bonesoul commented 4 years ago

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);

z4kn4fein commented 4 years ago

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.

bonesoul commented 4 years ago

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

z4kn4fein commented 4 years ago

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.

bonesoul commented 4 years ago

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