c# - Define custom autofacs with Unity (Container abstraction)? -
in ninject can do
kernel.bind(typeof(func<,>)).tomethod(createfunc).when(verifyfactoryfunction);
this means magic , reflection can do
public myconstructor(func<type, iresult> factory) { this.result = factory(typeof(sometype)); }
instead of
public myconstructor(iunitycontainer container) { this.result = container.resolve(typeof(sometype)); }
is possible unity? did extension method
public static void registercontainerabstraction<tto>(this iunitycontainer self) { self.registerinstance<func<type, tto>>(t => (tto)self.resolve(t)); }
you need call types want abstract container for, like
container.registercontainerabstraction<iresult>();
what ninject allows bit special feature , more of functional approach. di libraries in .net default take more object oriented approach means support creating , auto-wiring classes pretty good, while creation , currying of functions supported poorly.
so, out of box, there nothing in unity allow this, can solved creating custom interface , implementation:
// abstraction: part of core library public interface ifactory<tresult> { tresult create(type type); } // implementation: part of composition root private sealed createfuncfactory<tresult> : ifactory<tresult> { // since we're in composition root, okay depend // on container here. see: https://bit.ly/1mdalyg private readonly iunitycontainer container; public createfuncfactory(iunitycontainer container) { this.container = container; } public tresult create(type type) { return (tresult)container.resolve(type); } }
you can register in unity follows:
container.registertype(typeof(ifactory<>), typeof(createfuncfactory<>));
still however, if apply dependency injection correctly, there less need factory abstractions. still useful, need hand full in application. in respect, instead of having 1 generic func<,>
or ifactory<t>
abstraction, specify specific factories instead. makes more obvious going on , since should have few factories not lead lots of boilerplate code.
Comments
Post a Comment