c# - SimpleInjector - how to register many implementations of a generic type with LifetimeScopeLifestyle? -
while answering this question on couldn't figure out best technique registering many implementations of generic type instance of lifetimescopelifestyle
within simpleinjector.
the recommended method form of registration this:
container.registermanyforopengeneric(typeof(irepository<>), typeof(irepository<>).assembly);
but not allow instance of lifetimescopelifestyle
passed in.
below came know it's not resilient enough checking generic interface, not irepository<>
. can tell me how this?
public static void configure(container container) { var lifetimescope = new lifetimescopelifestyle(); container.register<iunitofwork, unitofwork>(lifetimescope); //this query needs improvement var registrations = type in typeof(irepository<>).assembly.getexportedtypes() typeof(irepository).isassignablefrom(type) && type.isclass && !type.isabstract service in type.getinterfaces() service.isgenerictype select new { service = service, implementation = type }; foreach (var registration in registrations) { container.register(registration.service, registration.implementation, lifetimescope); } }
tldr:
container.registermanyforopengeneric( typeof(irepository<>), lifetimescope, typeof(irepository<>).assembly);
first of all, query wrong. should have been:
var registrations = type in typeof(irepository<>).assembly.getexportedtypes() !service.isabstract !service.isgenerictypedefinition @interface in type.getinterfaces() @interface.isgenerictype @interface.getgenerictypedefinition() == typeof(irepository<>) select new { service = @interface, impl = type };
second, framework contains gettypestoregister
method fetch these types you, excludes decorator types:
var repositorytypes = opengenericbatchregistrationextensions.gettypestoregister( container, typeof(irepository<>), typeof(irepository<>).assembly); var registrations = type in repositorytypes @interface in type.getinterfaces() @interface.isgenerictype @interface.getgenerictypedefinition() == typeof(irepository<>) select new { service = @interface, impl = type };
but gets better, container contains overload of registermanyforopengeneric
method takes callback delegate allows registration follows:
container.registermanyforopengeneric( typeof(irepository<>), (service, impls) => { container.register(service, impls.single(), lifetimescope); }, typeof(irepository<>).assembly);
but importantly, framework contains registermanyforopengeneric
overloads takes in lifetime
. able simplify registration following:
container.registermanyforopengeneric( typeof(irepository<>), lifetimescope, typeof(irepository<>).assembly);
Comments
Post a Comment