Is it possible to return null in some situations for registered types in Autofac? -



Is it possible to return null in some situations for registered types in Autofac? -

i user autofac , wonder if possible come around dependencyresolutionexception thrown if instance returned registered type null? consider next example:

builder.register( c => c.resolve<httpcontextbase>().currenthandler itemplatepage ).instanceperhttprequest();

the illustration homecoming null if current handler (for illustration aspx-page visiting) isn't of type itemplatepage, , autofac throw dependencyresolutionexception if utilize resolveoptional alternative in way:

container.resolveoptional<itemplatepage>();

is there way come arond , behaviour autofac returns null instead of thowing exeption?

i have worked around adding isnull-proerty itemplatepage , instanciate it, this:

builder.register( c => c.resolve<httpcontextbase>().currenthandler itemplatepage ?? new templatepage(true) ).as<itemplatepage>().instanceperhttprequest();

and can work in way:

var templatepage = container.resolve<itemplatepage>(); if(!templatepage.isnull){ // stuff }

but not think optimal solution problem.

edit: grab error not alternative since utilize itemplatepage in constructors of other types resolve, , since using constructor injection resolve these types want them homecoming instance created constructor without itemplatepage parameter rather crash well.

the best way register service conditionally @ start of web request, e.g. (pseudocode):

void application_beginrequest() { var tp = httpcontext.currenthandler itemplatepage; if (tp != null) { var updater = new containerbuilder(); updater.registerinstance(tp); updater.update(containerprovider.requestlifetime.componentregistry); } }

this way, can create itemplatepage optional constructor parameter of components can utilize (itemplatepage tp = null) or utilize property injection/resolveoptional().

note there have been reliability improvements around these kinds of delayed registrations in autofac 2.5 recommend updating before using approach.

autofac

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

c# - Can ProtoBuf-Net deserialize to a flat class? -

javascript - Change element in each JQuery tab to dynamically generated colors -