Archive

Posts Tagged ‘StructureMap’

StructureMap Registries

October 28, 2010 Leave a comment

Registries allow you to extract the code you use to register components into different locations. Why is this important. Well I use always use a bootstrapper in my applications to load all the types for me. Now I can have each assembly if applicable define a registry of how to mapping in their own assembly.

Lets look at an example.

using System;
using System.Reflection;
using StructureMap;
using StructureMap.Configuration.DSL;

namespace StructureMapExamples
{

    public class EntityBase
    {
        public Guid Id { get; set; }
    }

    public class AggregateRoot : EntityBase { }

    public interface IRepository<TEntity>
        where TEntity : AggregateRoot
    {
        void Save(TEntity entity);
        void Update(TEntity entity);
        void Delete(TEntity entity);
        Guid Get(int id);
    }

    public class Customer : AggregateRoot
    {
        private string _name;

        public Customer(string name)
        {
            _name = name;
        }

        public void AssignName(string name)
        {
            _name = name;
        }
    }

    public class RepositoryBase<TEntity> : IRepository<TEntity>
        where TEntity : AggregateRoot
    {
        public void Save(TEntity entity)
        {
            Console.WriteLine("Saving TEntity: {0}", entity);
        }

        public void Update(TEntity entity)
        {
            Console.WriteLine("Update TEntity: {0}", entity);
        }

        public void Delete(TEntity entity)
        {
            Console.WriteLine("Delete TEntity: {0}", entity);
        }

        public Guid Get(int id)
        {
            Console.WriteLine("Getting TEntity: {0}", id);
            return Guid.Empty;
        }
    }

    public interface ICustomerRepository : IRepository<Customer>
    {

    }

    public class CustomerRepository : RepositoryBase<Customer>, ICustomerRepository
    {

        
    }

    public static class Bootstrapper
    {
        public static void WireUp(IContainer container)
        {
            container.Configure(x => x.Scan(y =>
                                                {

                                                    y.TheCallingAssembly();
                                                    y.LookForRegistries();

                                                }));   
        }
    }

    public class ExampleRegistry : Registry
    {
        public ExampleRegistry()
        {
            For<ICustomerRepository>().Use<CustomerRepository>();
        }
    }

    public class Program
    {

        static void Main(string[] args)
        {
            Program program = new Program();
            program.InitializeContainer();
            program.PrintWhatHasBeenRegisteredInStructureMap();

            Console.WriteLine("Press any key to quit");
            Console.ReadKey();
        }

        public void InitializeContainer()
        {
            Bootstrapper.WireUp(ObjectFactory.Container);
        }

        public void PrintWhatHasBeenRegisteredInStructureMap()
        {
            Console.WriteLine(ObjectFactory.WhatDoIHave());
        }

    }
}


The bootstrapper scans all assemblies for there registries and each registry know how to do their little bit of registration.

Blair..

StructureMap Automatic Registration Via Scanning – Part 1

October 28, 2010 Leave a comment

After looking at the previous examples you could imagine if you had a large project this would be a bit of a pain manually.
We can get StructureMap to automatically wire up most of this stuff for us. For example we can get StructureMap to Scan the assembly using the Scan method and wire up concrete class to their interfaces automatically. This maybe to basic for you and we will explorer more advanced usages in other sessions.

using System;
using System.Reflection;
using StructureMap;

namespace StructureMapSamples
{

    public class EntityBase
    {
        public Guid Id { get; set; }
    }

    public class AggregateRoot : EntityBase { }

    public interface IRepository<TEntity>
        where TEntity : AggregateRoot
    {
        void Save(TEntity entity);
        void Update(TEntity entity);
        void Delete(TEntity entity);
        Guid Get(int id);
    }

    public class Customer : AggregateRoot
    {
        private string _name;

        public Customer(string name)
        {
            _name = name;
        }

        public void AssignName(string name)
        {
            _name = name;
        }
    }

    public interface ICustomerRepository : IRepository<Customer>
    {

    }

    public class CustomerRepository : ICustomerRepository
    {

        public void Save(Customer entity)
        {
            Console.WriteLine("Saving Customer: {0}", entity);
        }

        public void Update(Customer entity)
        {
            Console.WriteLine("Update Customer: {0}", entity);
        }

        public void Delete(Customer entity)
        {
            Console.WriteLine("Delete Customer: {0}", entity);
        }

        public Guid Get(int id)
        {
            Console.WriteLine("Getting Customer: {0}", id);
            return Guid.Empty;
        }
    }

    public class Program
    {


        static void Main(string[] args)
        {
            Program program = new Program();
            program.InitializeContainer();
            program.PrintWhatHasBeenRegisteredInStructureMap();

            Console.WriteLine("Press any key to quit");
            Console.ReadKey();
        }

        public void InitializeContainer()
        {
            ObjectFactory.Configure(
                    x => x.Scan(
                            y =>
                            {
                                y.WithDefaultConventions();
                                y.Assembly(Assembly.GetExecutingAssembly());
                            }

                        )
                );
        }

        public void PrintWhatHasBeenRegisteredInStructureMap()
        {
            Console.WriteLine(ObjectFactory.WhatDoIHave());
        }


    }
}

The with defaults conventions does the automatic concrete class to interface map as mentioned before.

Hope this helps.
Blair

StructureMap Basic Debugging

October 28, 2010 Leave a comment

Following on from the last post. We will look at the example and see how we can get a print out of what has been registered. This is really useful if you are having issues and need to see what StructureMap is actually doing.

To see what has been registered check out the WhatDoIHave method on the ObjectFactory Class.

Here is the source code with the new functionality.

using System;
using StructureMap;

namespace StructureMapSamples
{
    public interface ILogger
    {
        void Log(string message);
    }

    public class RemoteLogger : ILogger
    {
        private readonly string _server;

        public int Port { get; set; }

        public RemoteLogger(string server)
        {
            _server = server;
            Port = 80;
        }

        public void Log(string message)
        {
            Console.WriteLine("Writing {0} to {1}:{2}", message,_server,Port);
        }
    }

    public class Program
    {
        

        static void Main(string[] args)
        {
            Program program = new Program();
            program.InitializeContainer();
            program.PrintWhatHasBeenRegisteredInStructureMap();
            program.RunExamplesWithCtorArgsPassedToTypeAndPropertyValuesSet();

            Console.WriteLine("Press any key to quit");
            Console.ReadKey();
        }

        public void InitializeContainer()
        {
            ObjectFactory.Configure(
                    x => x.For<ILogger>()
                          .Use<RemoteLogger>()
                          .Ctor<string>("server").Is("www.google.com")
                          .SetProperty(y => y.Port = 8080)
                );
        }

        public void PrintWhatHasBeenRegisteredInStructureMap()
        {
            Console.WriteLine(ObjectFactory.WhatDoIHave());
        }

        private void RunExamplesWithCtorArgsPassedToTypeAndPropertyValuesSet()
        {
            ILogger logger = ObjectFactory.GetInstance<ILogger>();
            logger.Log("Hello Google");
        }
    }
}

Also here is what the output from this method looks like.
================================================================================
===========================
Configuration Sources:

================================================================================
================================================================================
======================================================
PluginType Name
Description

——————————————————————————–
——————————————————————————–
——————————————————
Func`1 (Func`1)

Scoped as: Transient

15469a1d-2e3d-45d8-a850-e2eb37ea9187

——————————————————————————–
——————————————————————————–
——————————————————
IContainer (StructureMap.IContainer) 8d3565d0-8c7e-4bb2-8bea-9febbaf37fcd
Object: StructureMap.Container

Scoped as: Transient

8d3565d0-8c7e-4bb2-8bea-9febbaf37fcd
Object: StructureMap.Container

——————————————————————————–
——————————————————————————–
——————————————————
ILogger (StructureMapSamples.ILogger) 1abf6438-9b9a-4519-8651-51bd5dda1c69
Configured Instance of StructureMapSamples.RemoteLogger, StructureMapSamples,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
Scoped as: Transient

1abf6438-9b9a-4519-8651-51bd5dda1c69
Configured Instance of StructureMapSamples.RemoteLogger, StructureMapSamples,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
================================================================================
================================================================================
======================================================
Writing Hello Google to http://www.google.com:8080
Press any key to quit

Hope this helps.

Blair

StructureMap Manual Registration – Setting Properties

October 28, 2010 Leave a comment

Hi all back again with another example of using structure map manually. Were going to follow on from the last example.

If you have a concrete type that need a property set then you use the SetProperty Method and use an action lambda statement like below to set it up. EASY.

Pretty easy hey.

using System;
using StructureMap;

namespace StructureMapSamples
{
    public interface ILogger
    {
        void Log(string message);
    }

    public class RemoteLogger : ILogger
    {
        private readonly string _server;

        public int Port { get; set; }

        public RemoteLogger(string server)
        {
            _server = server;
            Port = 80;
        }

        public void Log(string message)
        {
            Console.WriteLine("Writing {0} to {1}:{2}", message,_server,Port);
        }
    }

    public class Program
    {
        

        static void Main(string[] args)
        {
            Program program = new Program();
            program.InitializeContainer();
            program.RunExamplesWithCtorArgsPassedToTypeAndPropertyValuesSet();

            Console.WriteLine("Press any key to quit");
            Console.ReadKey();
        }

        public void InitializeContainer()
        {
            ObjectFactory.Configure(
                    x => x.For<ILogger>()
                          .Use<RemoteLogger>()
                          .Ctor<string>("server").Is("www.google.com")
                          .SetProperty(y => y.Port = 8080)
                );
        }

        private void RunExamplesWithCtorArgsPassedToTypeAndPropertyValuesSet()
        {
            ILogger logger = ObjectFactory.GetInstance<ILogger>();
            logger.Log("Hello Google");
        }
    }
}

Hope this helps.

Blair

StructureMap Manual Registration – Setting Constructor Arguments

October 28, 2010 Leave a comment

Hi all back again with another example of using structure map manually.

If you have a concrete type that need a parameter set in its constructor it is really quite easy. Check out the following.

You use the Ctor(“name of parameter”).Is(“what is its value”)

Pretty easy hey.

using System;
using StructureMap;

namespace StructureMapSamples
{
    public interface ILogger
    {
        void Log(string message);
    }

    public class RemoteLogger : ILogger
    {
        private readonly string _server;

        public RemoteLogger(string server)
        {
            _server = server;
        }

        public void Log(string message)
        {
            Console.WriteLine("Writing {0} to {1}", message,_server);
        }
    }

    public class Program
    {
        

        static void Main(string[] args)
        {
            Program program = new Program();
            program.InitializeContainer();
            program.RunExamplesWithCtorArgsPassedToType();

            Console.WriteLine("Press any key to quit");
            Console.ReadKey();
        }

        public void InitializeContainer()
        {
            ObjectFactory.Configure(
                    x => x.For<ILogger>()
                          .Use<RemoteLogger>()
                          .Ctor<string>("server").Is("www.google.com")
                );
        }

        private void RunExamplesWithCtorArgsPassedToType()
        {
            ILogger logger = ObjectFactory.GetInstance<ILogger>();
            logger.Log("Hello Google");
        }
    }
}

Hope this helps.

Blair

StructureMap Manual Registration

October 26, 2010 Leave a comment

In an attempt to go and learn FubuMVC I decided to Learn the basics of StructureMap first. Being already fluent in Windsor this is a pain as now I am going to have to know how to use 2 containers.

I have put together a contrived example on how to manually register a concrete class against an interface and provided the basic code to do so.

I have other posts on IoC and containers if you want more information.

So heres the code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StructureMap;

namespace StructureMapSamples
{

    interface ILogger
    {
        void Log(string message);
    }

    class Logger : ILogger
    {
        public void Log(string message)
        {
            Console.WriteLine(message);
        }
    }

    public static class BootStrapper
    {
        public static void WireUp()
        {
            ObjectFactory.Initialize(
                    x => x.For<ILogger>().Use<Logger>()
                );
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            BootStrapper.WireUp();

            ILogger logger = ObjectFactory.GetInstance<ILogger>();
            logger.Log("Hello World From StructureMap");

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }

    }
}

As I get time between coding and learning Ruby I will add new posts with more advanced usages in the next few days.

Blair..