Minimal sample

Note: sample works only with version from repository.

Defining extensions

The first thing is need to do - define public contract of extension, that will be used for manipulating extension instances:
public interface IFruit
{
	string Name { get; }
}

Also, we need something to markup extension classes:
[MeansImplicitUse]
[BaseTypeRequired(typeof(IFruit))]
public class FruitAttribute : Attribute { }

MeansImplicitUse and BaseTypeRequired attributes is for ReSharper users. First of it marks that extension should not be marked as unused. Second force implementing/inheriting extension contract in marked extension.
The last element of the extension model - class that contains information about extension. It is required to define separate class for each type of extension, because its type used as a key inside standard registration infrastructure. Instance of this class created on the ground of extension attribute instance and registration context containing some data, including extension type. There is some precooked implementations, but you need to inherit from it.
public class FruitInfo : ElementInfo
{
	public FruitInfo([NotNull] Type type) : base(type) { }
}


Now, it's time to define extensions.
[Fruit]
public class Apple : IFruit
{
	public string Name
	{
		get { return "Apple"; }
	}
}

[Fruit]
public class Pear : IFruit
{
	public string Name
	{
		get { return "Pear"; }
	}
}

[Fruit]
public class Peach : IFruit
{
	public string Name
	{
		get { return "Peach"; }
	}
}

Using extensions

All extensibility infrastructure of R.SAT based on System.IServiceProvider. So, before anything can be done, it's need to create a root provider.
var root = new ServiceManager(true);

true in constructor argument specify, that provider also publish itself, so services will be pulished int it, if not overrided.
Next thing to do is creating strategy for extension discovery.
var strategy = root.CreateStrategy<FruitInfo, FruitAttribute>(type => new FruitInfo(type));

We specified info class, attribute, and lamdba, that creates instance of info class by extension type. There are some overloaded versions of this method, that allows more detailed control of process.
After creating strategy we can scan types and detect all extensions.
root.ScanExtensions(strategy);

Now, extensions retrieved and information about it stored in root service provider.
In order to create extension instances, there is special class - ExtensionsCache.
var cache = new ExtensionsCache<FruitInfo, IFruit>(root);

That is all. We can use our extensions.
foreach (var fruit in cache.GetAllElements())
	Console.WriteLine(fruit.Name);

Output:
Apple
Pear
Peach


Full sample

Last edited Jan 20, 2010 at 12:53 AM by AndrewVK, version 8

Comments

No comments yet.