Wednesday, January 16, 2008

Inversion of Control Example Structuremap

I am experimenting with IoC for the first time today. There are number of open source library out there . I chose Structuremap since I was introduced the concept by Jeremy D. Miller who was the author of the software last year in DevTeach. After I search around on the Internet to try to find some tutorials on the how it works with minimal amount of code to demonstrate how it works without success, I dicided to write my own. Here is the code:

<?xml version= "1.0" encoding="utf-8" ?>
<
StructureMap >
 <
Assembly Name="ConsoleApplication4" />
 
<
PluginFamily Assembly= "ConsoleApplication4" Type="ConsoleApplication4.IScheduler " DefaultKey="MyFirstScheduler">
   
<
Instance Type= "Daily" Key="MyFirstScheduler" />
 
</
PluginFamily >
</
StructureMap>

using System;
using
System.Data;
using
StructureMap;
namespace
ConsoleApplication4
{
    [Pluggable( "Daily")]
    public class DailyScheduler : IScheduler
   
{
        public DateTime GetNextRunTime( DateTime currentTime)
        {
            return DateTime.Now;
        }
    }

    public interface IScheduler
   
{
        DateTime GetNextRunTime(DateTime now);
    }

    class Program
   
{
        static void Main(string[] args)
        {
            IScheduler s = ObjectFactory.GetInstance<IScheduler>();
        }
    }
}

No comments: