Sunday, March 28, 2010

MEF and IoC/DI (4)

Let's look my first API class - DIResolverBase.

DIResolverBase Class


First, I need to create a class or a library project to define DI mapping relationships which will be used in my application. For example, DIResolver class is a class where I define MEF Import and Export properties. When the class is loaded as an assembly catalog or directory catalog to MEF, the parts or Import and Export mapping relationships are then loaded to MEF framework.

DIResolverBase class is a base class for DIResolver. The class is very simple. It implements IDisposable interface and contains a protected Add() method for holding disposable items.

When I started to use MEF, I was confused by the concept of disposing instances I retrieved from MEF or injected by MEF. At the start, I thought that an instance being requested from MEF was created by MEF and hence MEF should dispose them on application termination. However, it did not happen. In some cases, I had to explicitly dispose the instances retrieved from or injected by MEF in my application; otherwise, some resources such as files or connections would be left unclosed when my application is terminated.

Finally, I figured it out. It is wrong that I thought MEF created requested/injected instances, even MEF does create some instances in my DI library. It'll be much easier to explain it in an example: a console application and a DI library with a DIResolver class. The application only knows IProcessControler interface. The mapped instance is retrieved from the DI library. Here is a picture how the application and MEF work:


and here are some DI codes:

internal class DIResolver : DIResolverBase
{
  [Export]
  private IProcessController _exportController {
  get {
    var instance = new MyController( _log, _reader );
    // Add disposable obj to base created by this class
    // so it will be cleaned up when app terminates
    base.Add(instance);
    return instance;
  }

  [Import]
  private IDataReader _reader { get; set; }

  [Import]
  private ILog _log { get; set; }

}

At the start, the DI library is loaded to MEF as an assembly catalog. Then an instance of IProcessController is requested by the application (1). On the request, MEF resolves the mapping instance by creating an instance of DIResolver class because it found the Export for this type there (2). Hence the Import properties are initialized (3) with the injected instances (Export properties are defined in other DI libraries). Finally, a new the instance is created in the Export property getter (4). In this sense, MEF does create the instance of DIResolver class but not the instance of IProcessController. It is the DIResolver class that creates or news the instance. Therefore the clean up job should be done in this class.

Fortunately, MEF does the nice and cleaning up job when the application is terminated or the MEF container is disposed. MEF will call the dispose() method on all the composable parts, including DIResolver which is based on DIResolverBase. The base class provides the change of disposable.

The protected Add() API in the base class provide a way for the driving class to add any created and to-be-disposed instance to the base. The base class will do the cleaning up job on termination. In above example, you can see the customized DIResolver class is very simple and clean. In case of some instances which do not implement IDisposable interface but do have some resources to be released by other interfaces such as Close() or Disconnect(), the DIResolver class should override Dispose() method, do the customized cleaning job there, and call the base Dispose() method if any disposable instances were added.

One interesting feature of DIResolver class is that it can be an internal type class and the Import and Export properties can be private. This class is mainly used for MEF and rarely used as a public API. So I define it as a none-accessible class from the DI library. It is amazing that MEF can figure it out, i.e., to create DIResolver instances and to access to the private properties.

Read More...

Saturday, March 27, 2010

GitHub Repository as Source Code Repository

toolsWhile I was doing programming with XCode last night, one thing came to my mind: I need a repository to keep track of my source codes. It is not only a good way to save and track my changes, but it also provides a remote repository on Cloud to safely keep my project source codes. So I started to investigate options.

I have done some projects by using Google Code. I use it as a host for my public shared projects. I have not really used it as my source code repository. At work, I also use Subversion(SVN) as a alternative repository. Here is a list of SVN listing. For personal use, I heard many developers recommending GitHub as an alternative. So I gave it a try.

I created an account at GitHub. The basic account is free with .3GB space and no private repository. It provides update to fee-based private repositories. The following is what I have done.

First I need to install git. There is Mac version at Google. The installation is straightforward by running the installation pkg. A reboot is required to access to git in Terminal. I think the installation may add git to the terminal PATH.

The second step is to generate a SSH key. GitHub provides detail step-by-step information about this on Mac. I think this key is used to identify my Mac to a remote SVN repository.

The third step is to add the key to my GitHub account. The key is in my ~/.ssh folder. The generated SSH key is rsa type and the public key is in the file of id_rsa.pub. After adding my public key to my GitHub account, there is one file is created in my ~/.ssh folder as know_hosts.

That's all I have done so far. I have not reached the point to save my source codes in XCode to a repository yet.

Read More...

Friday, March 26, 2010

My New Web Site: Expense Log

By chance, I watched several YouTube videos about Google Site. I think I saw it long time ago and did not have any desire to create one. There are many web site provides and many of them are free. One interesting feature of Google's Sites is that is a Wiki based web site. People can leave comments there.

That's the feature I like. At present, I have been working on my first application. It will be released soon. So it is better to register a web site first. When the product is released, I'll update the site: Expense Log.

Read More...

Saturday, March 20, 2010

MEF and IoC/DI (3)

Here is the way how MEF interacts with the class. When there is a request to get an instance of IProcessController from MEF, MEF will create an instance of DIResolver since MEF knows the Export is defined in this DIResolver class. At the time when the instance is created, the two Import properties are injected with instances of IDataReader and ILog. Finally, the property getter marked as the Export type of IProcessController type is called with the result instance from MEF and then to the request.


You could place many or all Imports and Exports in one DIResolver class, but I prefer to define DIXXXResolver in a logical way so that it contains only the related mapping relationships, for example, DIContollerResolver for resolving the export of IProcessController, DIDataReaderResolver for the export of IDataReader, and DILogResolver for the export of ILog.

OK. I think is very clear about the concept of Export and Import as Parts in MEF in terms of DI. How are the parts (Import and Export) loaded to MEF so that the expected instances can be retrieved from the framework?

In MEF, all the parts are loaded to a DI container, which is called as CompositionContainer class. The container class interacts with Parts actually through another layer called as Cataglog. This is a very interesting and powerful structure. MEF currently supports four types of Catalog classes and they all inherited from ComposablePartCatalog class:


Those catalogs are straightforward by their names. For example, AssemblyCatalog is used for loading parts within an assembly; DirectoryCatalog for loading parts by specifying a folder or file pattern; TypeCatalog for loading a list of specific set of types; and AggregateCataglog for loading a list of catalogs. The first three are most commonly used ones. With this design of structure, Catalog class provides a wild range of strategies to load parts to a MEF container.

For example, I use the AssemblyCatalog to load a list of assemblies or DI libraries where DIXXXResolver classes are defined. I can also put some DI library and related library files in one folder, such as "DIExtensions". Then the folder is loaded by DirectoryCatalog. This makes it possible to dynamically add new extensions or update extensions without rebuilding or compiling my application source codes.

Although it is very easy to load Catalogs to MEF, you still need to understand and follow MEF pattern to do that. As you will find out, MEF contains a wild range of types, classes, interfaces and attributes. It may be very confusing or intimidating for beginners. I'll stop here about further explain MEF; instead, I'll show you three help classes I have created. Those classes provide very simple APIs to define DI mappings, to load DI catalogs, to retrieve instances, as well as other benefits you can get from them.

Still I think it will be very helpful to visit MEF class library and documentations when you see some MEF terms in my classes.

Read More...

Sunday, March 14, 2010

MEF and IoC/DI (2)

Let's explore how to use MEF as a DI framework.

Define Object Mapping Relationships


The documentation at CodePlex MEF project provides excellent information about its MEF structure, how to use it and examples. The information over there may be overwhelming, or more than you need if terms of DI. Here I'll explain MEF briefly just in the area of how to use MEF as a DI framework.

In MEF, the basic units are called as Composable Parts. A part can be either Export or Import. In the case of DI, this can be used to describe mapping relationships.


An Export is used to describe a composable part as a mapping relationship, for example, a class to a class type or interface type. In other words, it tells MEF how to get or create an instance for a class or an interface type.

An Import part, one the other hand, provides a gate way for a client get an instance as a class type or an interface type from MEF. For an import, MEF will inject an instance for a property or field variable if MEF has the knowledge of the corresponding Export part.

In MEF framework, Export and Import are used as attributes. Export attribute can be used to mark a class, a property or a method, while Import attribute can be used to a property, a field value or a constructor parameter.

In my DI practice, I use Export to define mapping relationships, and use Import in codes to let MEF to inject instances based on Export mappings. I mostly use Export/Import for property or field values, rarely for classes, methods or CROR parameters. One reason is that in most cases, I use third part components or reuse components I created before I knew MEF, therefore I cannot add Export/Import attributes to those classes or properties. Another reason is that those attributes actually have less relationship with their logic implementations. I would reluctant to impose other users to use my libraries with MEF binary files.

The advance of applying Export/Import to property or field values is that I can create one or a list of libraries, where only DI logic is described, nothing else. In addition to that, those libraries may have interfaces to get objects injected from MEF. Those libraries are the only places where I use MEF to define DI mappings and to provide a few of simple interfaces to retrieve objects for clients or applications.

As enough as I have said, I'll show you some examples how to use Export and Import attributes for DI mappings. Let's look at following example. Here are some interface definitions and a controller class definition:

public interface ILog {
  ...
}
...
public interface IDataReader {
  ...
}
...
public class MyController : IProcessController, IDisposable {
  // My implementation class
  ...
  // CTOR
  public MyControler(ILog log, IDataReader reader) {
     ...
  }
  ...
}


Then in a DI mapping library, I define a DIResolver class with some property variables marked as Export or Import:

internal class DIResolver {
  [Export]
  private IProcessController _exportController {
  get {
    return new MyController( _log, _reader );
  }

  [Import]
  private IDataReader _reader { get; set; }

  [Import]
  private ILog _log { get; set; }

}


There are some very interesting points in above codes. First, the class DIResolver can be internal, only visible within the project but not to the outside. It makes sense because I don't need to use this class as an API for any public uses. In addition to that, I can also hide Import and Export properties as private ones if I don't have intension to use them outside the class. MEF can access them.

I define the property _exportController as a mapping relationship between the interface of IProcessController and the implementation class MyContoller. The CTOR of MyController has two parametes: ILog and IDataReader. There are many ways to get instances for those parameters. Here I define two properties as the type of IDataReader and that of ILog, and they are accessible to the CTOR since they are local getters. The key point is that those two properties are also defined as setters and marked by Import attribute. As a result, MEF will be able to inject instances to them. Of course, the Exports for IDataReader and ILog have to be defined some other places such as DI libraries, where I define them in a similar way.

Read More...

Saturday, March 06, 2010

MEF and IoC/DI (1)

Inverse of Control (IoC) and Dependency Injection (DI) are widely used patterns in software development. Here I call DI in short for IoC/DI afterwards. I have used StructureMap in .Net as a framework to inject instances to my application, a nice way to decouple interfaces and implementations(see my previous blog posts). MEF(Managed Extensibility Framework) is another very hot topic in .Net recently. Now it is a part of new libraries in .Net Framework 4.0, and it is also available for .Net Framework 3.5. Actually, MEF started as an Open Source project at CodePlex by a group of Microsoft developers. It is claimed with more features than DI.

In the past weeks, I have tried MEF as an alternative way to StructureMap to provide DI. It works out very great. MEF may have much rich features than StructureMap since the later is mainly focused on DI while the former is on the extensibility and discovery ability. Since I am more familiar with DI, therefore, in the view of ID, in this and following posts, I’ll explain in detail how I use MEF as a DI framework.

Overview


Let's stand back a few of steps to get a big picture of implementation of DIs in an application. From my past experience of using StructureMap, I treat it as a library to hold a DI container in cloud.

First, I provide it with information about mapping relations of class to class or interface to class to the container. Then either I fetch instances by interfaces or class from the container directly whenever I need them, or I mark my codes with some kinds of indicators such as attribute so that the cloud will be able to inject appropriate instances automatically. As a result, I would not need to know how instances are created, nor need I to have any knowledge of what actual instances are mapped. This will let me to concentrate on my business logic or working on components individually.



The above is the picture I perceive. With this picture in mind, I found that MEF works in a similar way. I don’t need to change my interface library and components (3), nor my business implementation or application (4). What I need to do is to understand the structure and the way of how to add/load my mapping relationships through the block (2) to the new container (1), and understand how to request instances from the DI framework to my application (4), or to construct my application so that instances will be able to inject to "magically".

In the above picture, there are two doted arrows, which mean that there are two ways to call or reference to each other. One is direct call or request. For example, you can write codes to let the container to know what the mappings are, and you can make a call to the container to get an instance by type. In other words, you have direct access to the container. Another way is that you don't need to write codes to do any direct call at all. Most DI frameworks provide some ways to mark dependencies and injects so that DI framework will be able to detect or load mappings and inject instances automatically. For example, you may construct a mapping configuration file, or add some special attributes to your classes, property variables, constructors or method parameters. Both MEF and StrcutreMap support these two ways; however, they provide different strategies and implementations in terms of how to describe the mappings and to provide injections.

In this and following posts, I'll discuss how to use MEF to describe mappings and injections. My practice only exposes the tip of iceberg, as MEF has much rich infrastructure and features. Even though, I think my DI exercise may help you better to understand MEF. During my exploration, I have done several times of refactory of my codes, which were quite rewarding learning experience.

Read More...