. Net mef entry-level example,. netmef entry-level example
I like to start with simple examples to learn new things. I feel that understanding and getting started will be faster. This article will record a simple mef example. Baidu, google has gone.
Mef does not need to re-code when you adjust some functions, but only needs to replace the corresponding dll.
MefDemo. Core: returns the current date in the format of yyyy-MM-dd.
MefDemo. Core2: returns the current date in the format of yyyy/MM/dd.
MefDemo. InterFace: InterFace, intermediate InterFace between the caller and the implementer
MefDemo. Web: An MVC program used for testing
I. Code in MefDemo. Core
Ii. Code in MefDemo. Core2
Iii. MefDemo. InterFace code
Iv. MefDemo. Web code
The code in Global. asax is written in red box, and the rest is automatically generated by.
The code of the MefDependencySolver class is as follows:
public class MefDependencySolver : IDependencyResolver
{
private readonly ComposablePartCatalog _catalog;
private const string MefContainerKey = "MefContainerKey";
public MefDependencySolver(ComposablePartCatalog catalog)
{
_catalog = catalog;
}
public CompositionContainer Container
{
get
{
if (!HttpContext.Current.Items.Contains(MefContainerKey))
{
HttpContext.Current.Items.Add(MefContainerKey, new CompositionContainer(_catalog));
}
CompositionContainer container = (CompositionContainer)HttpContext.Current.Items[MefContainerKey];
HttpContext.Current.Application["Container"] = container;
return container;
}
}
#region IDependencyResolver Members
public object GetService(Type serviceType)
{
string contractName = AttributedModelServices.GetContractName(serviceType);
return Container.GetExportedValueOrDefault<object>(contractName);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return Container.GetExportedValues<object>(serviceType.FullName);
}
#endregion
}
In the last step, we can test it by finding a controller.
After testing, we will find that when we are in MefDemo. the binfile of the Web Project is stored in MefDemo. core. in dll, We ViewBag. the value obtained by date is the year-month-number. When we put the MefDemo in the binfile. core. replace dll with MefDemo. when Core2.dll is used, ViewBag. the value of date is the year, month, and number. Now, the Getting Started demo is here.