First, the simple question.
Is it possible to receive an event when MEF (System.ComponentModel.Composition) creates an instance of a part?
When this occurs I want to reflect over the created object and wire up various attributes. In Spring.Net this is possible with the IObjectPostProcessor interface.
The background is that I trying to implement Publisher/Subscriber pattern in MEF. Basically the subscriber class does this:
class MyContoller
{
[Command("Print")]
public void Print() { ... }
[Command("PrintPreview")]
public void PrintPreview() { ... }
}
And I want to detect when MyController is instantiated and wire up any methods that have the CommandAttribute.
A publisher, such as a menu item, would do Command.Get("Print").Fire() to publish the aforementioned event.
Second Question
Maybe there is an alternative pattern in MEF that I am missing!!!
I've seen some postings about MEF, Prism and the Event Aggregate, but it appears fairly complex.
FYI
Just for reference, here's the original for Spring.Net implementation:
class CommandAttributeProcessor : IObjectPostProcessor
{
static ILog log = LogManager.GetLogger(typeof(CommandAttributeProcessor));
public object PostProcessAfterInitialization(object instance, string objectName)
{
foreach (MethodInfo methodInfo in instance.GetType().GetMethods())
{
foreach (CommandAttribute attr in methodInfo.GetCustomAttributes(typeof(CommandAttribute), true))
{
if (log.IsDebugEnabled)
log.Debug(String.Format("Binding method '{0}.{1}' to command '{2}'.", instance.GetType().Name, methodInfo.Name, attr.CommandName));
Command command = Command.Get(attr.CommandName);
command.Execute += (EventHandler) Delegate.CreateDelegate(typeof(EventHandler), instance, methodInfo);
}
}
return instance;
}
public object PostProcessBeforeInitialization(object instance, string name)
{
return instance;
}
}
This may not help, but the part itself can receive notification when it is fully composed:
Automatically call method after part has been composed in MEF
Also, you probably already know this (and it might not really be related to what you are trying to do), but you can decorate your Exports and Imports such the concrete implementations are named. So, you could have an exported class something like this:
[Export("Print", typeof(IPlugin))]
[PartCreationPolicy(CreationPolicy.Shared)]
class Print : IPlugin
{
.
.
.
public Fire()
{
//Do something;
}
}
class PrintMenuItem
{
IPlugin _plugin;
[ImportingConstructor]
PrintMenuItem([Import("Print", typeof(IPlugin)] plugin)
{
_plugin = plugin;
}
void Execute()
{
_plugin.Fire();
}
}
You can use InterceptingCatalog from MEF Contrib (MEF Contrib on codeplex or you can install it by nuGet) and implement IExportedValueInterceptor interface to wire up methods that have CommandAttribute:
//using System.ComponentModel.Composition;
//using System.ComponentModel.Composition.Hosting;
//using MefContrib.Hosting.Interception;
//using MefContrib.Hosting.Interception.Configuration;
public class CommandAttributeProcessor : IExportedValueInterceptor
{
public object Intercept(object value)
{
foreach (MethodInfo methodInfo in value.GetType().GetMethods())
{
foreach (CommandAttribute attr in methodInfo.GetCustomAttributes(typeof(CommandAttribute), true))
{
// do something with command attribute
}
}
return value;
}
}
and at creating MEF catalog, you need to add interception configuration with your interceptor (CommandAttributeProcessor) and wrap your catalog in InterceptingCatalog like this:
InterceptionConfiguration interceptionConfiguration = new InterceptionConfiguration();
interceptionConfiguration.AddInterceptor(new CommandAttributeProcessor());
InterceptingCatalog interceptingCatalog = new InterceptingCatalog(assemblyCatalog, interceptionConfiguration);
CompositionContainer container = new CompositionContainer(interceptingCatalog);
Related
Assume I have a plugin interface like this:
// PluginInterface.cs
interface Plugin
{
bool Check_When_Loaded(string q);
}
static class PluginList
{
public static List<Plugin> list = new List<Plugin>();
}
And I use it in MainWindow.cs:
// MainWindow.cs
private void Window_Loaded(object sender, RoutedEventArgs e)
{
foreach (var p in PluginList.list)
{
if (p.Check_When_Loaded(q.Text)) break;
}
}
Assume I write a plugin LovelyPlugin.cs:
// LovelyPlugin.cs
class LovelyPlugin : Plugin
{
public bool Check_When_Loaded(string q)
{
return true;
}
}
What I need is when I add LovelyPlugin.cs to C# project then complie, a 'LovelyPlugin' instance is added automaticly to PluginList.list, and if I remove this file then complie, there is no trace of LovelyPlugin in application at all.
I have a C# solution that have some simliar project (Light, Standard, Extra,...). All the difference between them is one have or doesn't have some plugin file. All .cs files is add as link to all these project and I want to build all these project concurently.
I can use #define and #if condition then build each project seperately. But I wonder if there is any way to fit my need just by add/remove plugin file without make any change in other source code file for each project. Any help would be appreciated!
You could use MEF...
Start by referencing System.ComponentModel.Composition
Read up on the MEF documentation regarding Imports and Exports. In your case, the Plugins are "Exports". We can use the [InheritedExport] attribute to allow every concrete object that implements IPlugin to be exportable.
// IPlugin.cs
using System.ComponentModel.Composition;
[InheritedExport]
public interface IPlugin
{
bool Check_When_Loaded(string q);
}
Your concrete implementation of IPlugin doesn't change.
// LovelyPlugin.cs
class LovelyPlugin : IPlugin
{
public bool Check_When_Loaded(string q)
{
return true;
}
}
I eliminated your static PluginList class to simplify the example. Below you can see how the Main Form is "Importing" any implmentations of IPlugin found in the Assembly. If you add (or remove) additional concrete implementations of IPlugin and recompile, the list will reflect accordingly.
// MainWindow.cs
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
public partial class Form1 : Form
{
[ImportMany]
public List<IPlugin> list = new List<IPlugin>();
public Form1()
{
InitializeComponent();
}
private void WindowLoaded(object sender, EventArgs e)
{
var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
var container = new CompositionContainer(catalog);
container.ComposeParts(this);
foreach (var p in list)
{
if (p.Check_When_Loaded(this.Name)) break;
}
}
}
Add this to your PluginList class:
// using System.Reflection;
static PluginList()
{
list.AddRange(
from t in Assembly.GetAssembly(typeof(PluginList)).GetTypes()
where t.IsClass && t.GetInterfaces().Contains(typeof(Plugin))
select new Func<Plugin>(() => {
try
{
return (Plugin)t.GetConstructor(new Type[] { }).Invoke(new object[] { });
}
catch
{
return null;
}
})());
}
Essentially at runtime this will:
Get all types in the current project (the from line).
Filter these types to only include classes that implement your Plugin interface (the where line).
It attempts to construct one of each of these plugin classes with a default constructor (zero-argument) in the select line. If you want exceptions for failed constructors, you can simply change the return null;.
Add all such constructed plugins to your list.
I am using windsor castle as my IoC container, and has run in to a bit of a problem.
First of all - i know about: Castle Windsor: How to prevent circular references in factory-created objects were the created objects refers back to the factory
But since circular reference is considered as "Code Smell" and i should consider refactoring app architecture i am asking anyway.
I have very similar situation:
public class OperationsFactory
{
private GeneralSettingsManager m_generalSettings;
private Dictionary<OperationType, OperationCreatorBase> m_creators;
public OperationsFactory(IKernel container)
{
m_generalSettings = container.Resolve<GeneralSettingsManager>();
var creators = container.ResolveAll<OperationCreatorBase>(); //FIRST DEPENDENCY
foreach (var creator in creators)
{
m_creators.Add(creator.CreatorOperationType, creator);
}
}
.
.
.
private OperationCreatorBase GetCreator(OperationType operationType)
{
return m_creators[operationType];
}
}
Now i would like to take in code this OperationFactory from windsor container so i can easily read all the successors of OperationCreatorBase.
now there is a code for OperationCreator:
public class ConvertToFullOperationCreator : OperationCreatorBase
{
private OperationsFactory m_operationsFactory;
private SomeHelper m_someHelper;
public ConvertToFullOperationCreator(IKernel container)
{
m_operationsFactory = container.Resolve<OperationsFactory>(); //SECOND dependency which causes error
m_someHelper = container.Resolve<SomeHelper>();
}
public override OperationType CreatorOperationType
{
get { return OperationType.SomeOperation2; }
}
public override List<OperationBase> CreateOperation(FileData fileData)
{
//HERE I WANT TO USE FACTORY to get creators for SUBOPERATIONS
var creator1 = m_operationsFactory.GetCreator(OperationType.SomeSuboperation1);
creator1.CreateOperation(fileData);
.
.
.
m_someHelper.DoSomething(fileData);
var creator2 = m_operationsFactory.GetCreator(OperationType.SomeSuboperation2);
creator2.CreateOperation(fileData);
.
.
.
}
}
I really want to use windsor castle for both of this classes because i am using more components (such as SomeHelper in creator... and more). In factory class i am using nice method ResolveAll provided by IKernel.
There is obvious constructor circular reference but i cant figure out, whats wrong with this component design and most important - how to make this runnable.
I know i can do it with Property Injection on both sides but this kills this nice dependency injection feature, so thats why the answer said in upper stackoverflow question wont solve my problem. Am i missing something?
Is there any suggestion how to redesign those two components or how to Split the "C" class said in nice article about circular reference here: http://misko.hevery.com/2008/08/01/circular-dependency-in-constructors-and-dependency-injection/
In order to solve cyclic dependency you should inject Func<OperationsFactory> instead of OperationsFactory via constructor (or resolve using IKernel/ IWindsorContainer).
public class ConvertToFullOperationCreator : OperationCreatorBase
{
private Func<OperationsFactory> get_operationsFactory;
private SomeHelper m_someHelper;
public ConvertToFullOperationCreator(
SomeHelper someHelper,
Func<OperationsFactory> get_operationsFactory)
{
this.get_operationsFactory = get_operationsFactory
m_someHelper = someHelper;
}
public override List<OperationBase> CreateOperation(FileData fileData)
{
var m_operationsFactory = get_operationsFactory()
// Here you can place all your code
var creator1 = m_operationsFactory
.GetCreator(OperationType.SomeSuboperation1);
...
var creator2 = m_operationsFactory
.GetCreator(OperationType.SomeSuboperation2);
...
}
}
First OperationsFactory should be registered, then Func<OperationsFactory>.
container.Register(Component.For<Func<OperationsFactory>>()
.UsingFactoryMethod(container =>
{
Func<OperationsFactory> func = container.Resolve<OperationsFactory>;
return func;
}));
I've already answered the similar question Cyclic dependency with Castle Windsor IoC for NHibernate ISession. You can find more details there.
If you already use IoC container it is better to inject instances of concrete types via constructor instead of IKernel. IKernel is a part of your infrastructure.
In order to resolve IEnumerable<T> CollectionResolver can be used.
public class OperationsFactory
{
private GeneralSettingsManager m_generalSettings;
private Dictionary<OperationType, OperationCreatorBase> m_creators;
public OperationsFactory(
GeneralSettingsManager generalSettings,
IEnumerable<OperationCreatorBase> creators)
{
m_generalSettings = generalSettings;
foreach (var creator in creators)
{
m_creators.Add(creator.CreatorOperationType, creator);
}
}
...
}
EDIT :
If you cannot register Func<OperationsFactory> you can create it in the constructor in order to load OperationsFactory lazily.
public class ConvertToFullOperationCreator : OperationCreatorBase
{
private Func<OperationsFactory> get_operationsFactory;
private SomeHelper m_someHelper;
public ConvertToFullOperationCreator(
IKernel container)
{
this.get_operationsFactory = () => container.Resolve<OperationsFactory>;
m_someHelper = container.Resolve<SomeHelper>();
}
public override List<OperationBase> CreateOperation(FileData fileData)
{
var m_operationsFactory = get_operationsFactory()
// Here you can place all your code
var creator1 = m_operationsFactory
.GetCreator(OperationType.SomeSuboperation1);
...
var creator2 = m_operationsFactory
.GetCreator(OperationType.SomeSuboperation2);
...
}
}
C#. I have a base class called FileProcessor:
class FileProcessor {
public Path {get {return m_sPath;}}
public FileProcessor(string path)
{
m_sPath = path;
}
public virtual Process() {}
protected string m_sath;
}
Now I'd like to create to other classes ExcelProcessor & PDFProcessor:
class Excelprocessor: FileProcessor
{
public void ProcessFile()
{
//do different stuff from PDFProcessor
}
}
Same for PDFProcessor, a file is Excel if Path ends with ".xlsx" and pdf if it ends with ".pdf". I could have a ProcessingManager class:
class ProcessingManager
{
public void AddProcessJob(string path)
{
m_list.Add(Path;)
}
public ProcessingManager()
{
m_list = new BlockingQueue();
m_thread = new Thread(ThreadFunc);
m_thread.Start(this);
}
public static void ThreadFunc(var param) //this is a thread func
{
ProcessingManager _this = (ProcessingManager )var;
while(some_condition) {
string fPath= _this.m_list.Dequeue();
if(fPath.EndsWith(".pdf")) {
new PDFProcessor().Process();
}
if(fPath.EndsWith(".xlsx")) {
new ExcelProcessor().Process();
}
}
}
protected BlockingQueue m_list;
protected Thread m_thread;
}
I am trying to make this as modular as possible, let's suppose for example that I would like to add a ".doc" processing, I'd have to do a check inside the manager and implement another DOCProcessor.
How could I do this without the modification of ProcessingManager? and I really don't know if my manager is ok enough, please tell me all your suggestions on this.
I'm not really aware of your problem but I'll try to give it a shot.
You could be using the Factory pattern.
class FileProcessorFactory {
public FileProcessor getFileProcessor(string extension){
switch (extension){
case ".pdf":
return new PdfFileProcessor();
case ".xls":
return new ExcelFileProcessor();
}
}
}
class IFileProcessor{
public Object processFile(Stream inputFile);
}
class PdfFileProcessor : IFileProcessor {
public Object processFile(Stream inputFile){
// do things with your inputFile
}
}
class ExcelFileProcessor : IFileProcessor {
public Object processFile(Stream inputFile){
// do things with your inputFile
}
}
This should make sure you are using the FileProcessorFactory to get the correct processor, and the IFileProcessor will make sure you're not implementing different things for each processor.
and implement another DOCProcessor
Just add a new case to the FileProcessorFactory, and a new class which implements the interface IFileProcessor called DocFileProcessor.
You could decorate your processors with custom attributes like this:
[FileProcessorExtension(".doc")]
public class DocProcessor()
{
}
Then your processing manager could find the processor whose FileProcessorExtension property matches your extension, and instantiate it reflexively.
I agree with Highmastdon, his factory is a good solution. The core idea is not to have any FileProcessor implementation reference in your ProcessingManager anymore, only a reference to IFileProcessor interface, thus ProcessingManager does not know which type of file it deals with, it just knows it is an IFileProcessor which implements processFile(Stream inputFile).
In the long run, you'll just have to write new FileProcessor implementations, and voila. ProcessingManager does not change over time.
Use one more method called CanHandle for example:
abstract class FileProcessor
{
public FileProcessor()
{
}
public abstract Process(string path);
public abstract bool CanHandle(string path);
}
With excel file, you can implement CanHandle as below:
class Excelprocessor: FileProcessor
{
public override void Process(string path)
{
}
public override bool CanHandle(string path)
{
return path.EndsWith(".xlsx");
}
}
In ProcessingManager, you need a list of processor which you can add in runtime by method RegisterProcessor:
class ProcessingManager
{
private List<FileProcessor> _processors;
public void RegisterProcessor(FileProcessor processor)
{
_processors.Add(processor)
}
....
So LINQ can be used in here to find appropriate processor:
while(some_condition)
{
string fPath= _this.m_list.Dequeue();
var proccessor = _processors.SingleOrDefault(p => p.CanHandle(fPath));
if (proccessor != null)
proccessor.Process(proccessor);
}
If you want to add more processor, just define and add it into ProcessingManager by using
RegisterProcessor method. You also don't change any code from other classes even FileProcessorFactory like #Highmastdon's answer.
You could use the Factory pattern (a good choice)
In Factory pattern there is the possibility not to change the existing code (Follow SOLID Principle).
In future if a new Doc file support is to be added, you could use the concept of Dictionaries. (instead of modifying the switch statement)
//Some Abstract Code to get you started (Its 2 am... not a good time to give a working code)
1. Define a new dictionary with {FileType, IFileProcessor)
2. Add to the dictionary the available classes.
3. Tomorrow if you come across a new requirement simply do this.
Dictionary.Add(FileType.Docx, new DocFileProcessor());
4. Tryparse an enum for a userinput value.
5. Get the enum instance and then get that object that does your work!
Otherwise an option: It is better to go with MEF (Managed Extensibility Framework!)
That way, you dynamically discover the classes.
For example if the support for .doc needs to be implemented you could use something like below:
Export[typeof(IFileProcessor)]
class DocFileProcessor : IFileProcessor
{
DocFileProcessor(FileType type);
/// Implement the functionality if Document type is .docx in processFile() here
}
Advantages of this method:
Your DocFileProcessor class is identified automatically since it implements IFileProcessor
Application is always Extensible. (You do an importOnce of all parts, get the matching parts and Execute.. Its that simple!)
I have two .NET parties who needs be bound by a contract. Now, party1 and party2 need to be able call some methods on each other (most of it is calls and reporting result back). I have duplex contract in mind, but the parties are not using WCF.
Is there a design pattern for this?
Edit
The parties are part of the same application. I create the application (party1) and someone else creates a dll (party2) that I load dynamically. Now, both of us should be able to call methods on each other. So, I am out to create an interface contract between us. The intent is to know whether there is a know pattern to do that?
A common solution is to use some kind of pub/sub pattern. By doing so you can avoid circular dependencies.
Basically you create some kind of class which are used to subscribe on events (and publish them).
So both your classes does something like this (but with different events):
public class ClassA : IEventHandler<UserCreated>
{
IEventManager _eventManager
public ClassA(IEventManager manager)
{
// I subscribe on this event (which is published by the other class)
manager.Subscribe<UserCreated>(this);
_eventManager = manager;
}
public void Handle(UserCreated theEvent)
{
//gets invoked when the event is published by the other class
}
private void SomeInternalMethod()
{
//some business logic
//and I publish this event
_eventManager.Publish(new EmailSent(someFields));
}
}
The event manager (simplified and not thread safe):
public class EventManager
{
List<Subscriber> _subscribers = new List<Subscriber>();
public void Subscribe<T>(IEventHandler<T> subscriber)
{
_subscribers.Add(new Subscriber{ EventType = typeof(T), Subscriber = subscriber});
}
public void Publish<T>(T theEvent)
{
foreach (var wrapper in subscribers.Where(x => x == typeof(theEvent)))
{
((IEventHandler<T>)wrapper.Subscriber).Handle(theEvent);
}
}
}
The small wrapper:
public class Subscriber
{
public Type EventType;
public object Subscriber;
}
Voila. the two classes are now loosely coupled from each other (while still being able to communicate with each other)
If you use an inversion of control container it get's easier since you can simplify the event manager and just use the container (service location) to resolve all subscribers:
public class EventManager
{
IYourContainer _container;
public EventManager(IYourContainer container)
{
_container = container;
}
public void Publish<T>(T theEvent)
{
foreach (var subscriber in _container.ResolveAll<IEventHandler<T>>())
{
subscriber.Handle(theEvent);
}
}
}
I think you can use next logic:
Class1: Interface1 , Class2:Interface2,
class Manager{
public Manager(Interface1 managedPart1,Interface2 managedPart2){
... some logic for connect to interfaces
}
}
This way reminds me pattern Bridge, but this is very subjective
I am trying to learn Unity Interceptors and I am having a hard go of it.
Say I have an interface like this:
public interface IMyInterface
{
void SomeMethod();
}
And I have an unknown number of classes that implement that interface like this:
public class SpecificClass1 : IMyInterface
{
public void SomeMethod()
{
Console.WriteLine("Method Called");
}
}
I am looking for a way to say, "for all instance of IMyInterface (I don't want to enumerate them), when SomeMethod is called run my interceptor.
It is the Non-Enumeration of the classe that is giving me trouble. (There are plenty of examples if you can enumerate all your classes.)
I have read of Type Interception, but I can't seem to find out if it will do what I am looking for.
Any Unity experts out there know how to do what I am looking for?
You could create InterceptionBehavior then register it on specific class. Note you could filter executing methods in Invoke thru IMethodInvocation input
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;
using NUnit.Framework;
namespace UnitTests
{
[TestFixture]
public class ForTest
{
[Test]
public void Test()
{
IUnityContainer container = new UnityContainer().AddNewExtension<Interception>();
container.RegisterType<IMyInterface, SpecificClass1>(
new Interceptor<InterfaceInterceptor>(),
new InterceptionBehavior<MyInterceptionBehavior>());
var myInterface = container.Resolve<IMyInterface>();
myInterface.SomeMethod();
}
}
public interface IMyInterface
{
void SomeMethod();
}
public class SpecificClass1 : IMyInterface
{
#region IMyInterface
public void SomeMethod()
{
Console.WriteLine("Method Called");
}
#endregion
}
public class MyInterceptionBehavior : IInterceptionBehavior
{
public bool WillExecute
{
get { return true; }
}
#region IInterceptionBehavior
public IEnumerable<Type> GetRequiredInterfaces()
{
return Enumerable.Empty<Type>();
}
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
{
IMethodReturn result = getNext()(input, getNext);
Console.WriteLine("Interception Called");
return result;
}
#endregion
}
}
Console output
Method Called
Interception Called
More about Interception with Unity
#GSerjo, has outlined the Unity interception approach which works well. If you wanted to automate the configuration of interception you can use a UnityContainerExtension to automatically wire up all the interface interception as well as the behaviors. If you wanted to get into more specific interception (method names, signatures, return values etc.) then you would probably need to look at Policy Injection (using matching rules with CallHandlers).
So in this case the container extension would look like:
public class UnityInterfaceInterceptionRegisterer : UnityContainerExtension
{
private List<Type> interfaces = new List<Type>();
private List<IInterceptionBehavior> behaviors =
new List<IInterceptionBehavior>();
public UnityInterfaceInterceptionRegisterer(Type interfaceType,
IInterceptionBehavior interceptionBehavior)
{
interfaces.Add(interfaceType);
behaviors.Add(interceptionBehavior);
}
public UnityInterfaceInterceptionRegisterer(Type[] interfaces,
IInterceptionBehavior[] interceptionBehaviors)
{
this.interfaces.AddRange(interfaces);
this.behaviors.AddRange(interceptionBehaviors);
ValidateInterfaces(this.interfaces);
}
protected override void Initialize()
{
base.Container.AddNewExtension<Interception>();
base.Context.Registering +=
new EventHandler<RegisterEventArgs>(this.OnRegister);
}
private void ValidateInterfaces(List<Type> interfaces)
{
interfaces.ForEach((i) =>
{
if (!i.IsInterface)
throw new ArgumentException("Only interface types may be configured for interface interceptors");
}
);
}
private bool ShouldIntercept(RegisterEventArgs e)
{
return e != null && e.TypeFrom != null &&
e.TypeFrom.IsInterface && interfaces.Contains(e.TypeFrom);
}
private void OnRegister(object sender, RegisterEventArgs e)
{
if (ShouldIntercept(e))
{
IUnityContainer container = sender as IUnityContainer;
var i = new Interceptor<InterfaceInterceptor>();
i.AddPolicies(e.TypeFrom, e.TypeTo, e.Name, Context.Policies);
behaviors.ForEach( (b) =>
{
var ib = new InterceptionBehavior(b);
ib.AddPolicies(e.TypeFrom, e.TypeTo, e.Name, Context.Policies);
}
);
}
}
}
Then you could use it like so:
IUnityContainer container = new UnityContainer()
.AddExtension(new UnityInterfaceInterceptionRegisterer(
new Type[] { typeof(IMyInterface),
typeof(IMyOtherInterface) },
new IInterceptionBehavior[] { new MyInterceptionBehavior(),
new AnotherInterceptionBehavior() }
));
container.RegisterType<IMyInterface, SpecificClass1>();
var myInterface = container.Resolve<IMyInterface>();
myInterface.SomeMethod();
Now when the interface is registered the appropriate interception policies will also be added to the container. So in this case if the interface registered is of type IMyInterface or IMyOtherInterface then policies will be setup for interface interception and the Interception Behaviors MyInterceptionBehavior and AnotherInterceptionBehavior will also be added.
Note that Unity 3 (released after this question/answer) added a Registration by Convention feature that can do what this extension does (without having to write any custom code). An example from the Developer's Guide to Dependency Injection Using Unity:
var container = new UnityContainer();
container.AddNewExtension<Interception>();
container.RegisterTypes(
AllClasses.FromLoadedAssemblies().Where(
t => t.Namespace == "OtherUnitySamples"),
WithMappings.MatchingInterface,
getInjectionMembers: t => new InjectionMember[]
{
new Interceptor<VirtualMethodInterceptor>(),
new InterceptionBehavior<LoggingInterceptionBehavior>()
});
Setting up interception requires multiple actions incl. configuration of intercepted types, policies and handlers.
First see Using Interception in Applications for general details about the types of situations where interception is supported (with or without a DI container for example). Then see Type Interception for more details about the supported type interceptors. Especially take note of what interceptors can be used with the type of your class (otherwise the handlers will never trigger).
When you have decided what interceptor to use, configure it and create a sufficient call handler as per the links above. If you still have trouble at this point, post a more detailed question. If you have already done this, please post the configs and code as "non-enumeration of the classe" simply does not give any hints what you are actually asking. Do you by any chance mean with "enumeration" that you assign a attribute-driven policy and are unable to achieve what you want without it?