c# - Using Autofac's ReplaceInstance with interface types -


according documentation, can use activating event "switch instance or wrap in proxy," haven't been able work.

here's i've tried:

[testfixture] public class replaceinstancetest {     public interface isample { }     public class sample : isample { }     public class proxiedsample : isample {         private readonly isample _sample;         public proxiedsample(isample sample) {             _sample = sample;         }     }      [test]     public void replaceinstance_can_proxy_for_interface_type()     {         var builder = new containerbuilder();         builder.registertype<sample>()                .as<isample>()                .onactivating(x =>                   x.replaceinstance(new proxiedsample(x.instance)))                .singleinstance();         var container = builder.build();          var sample = container.resolve<isample>();         assert.that(sample, is.instanceof<proxiedsample>());     }  } 

the above results in class cast exception because autofac trying cast proxiedsample sample instance, not.

is possible use replaceinstance on activatingevent proxy object in autofac (2.6 or 3.0)?

i know it's possible use registerdecorator, actual implementation both configures , conditionally proxies, i'd prefer use activating event, if it's possible.

travis responded on autofac list detailing of challenges surrounding this. between comments , nsgaga's suggestions came following workaround:

[test] public void replaceinstance_can_proxy_for_interface_type_when_using_multi_stage_registration() {     var builder = new containerbuilder();     builder.registertype<sample>().asself();     builder.register(c => (isample)c.resolve<sample>())            .onactivating(x => x.replaceinstance(new proxiedsample(x.instance)))            .singleinstance();     var container = builder.build();      var sample = container.resolve<isample>();     assert.that(sample, is.instanceof<proxiedsample>()); } 

it's possible make registration more compact:

builder.register<isample>(c => new sample()).onactivating(/*...*/); 

the downfall of approach if sample constructor changes registration have change well, avoided additional registration of concrete type.


Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -