Home > Development > StructureMap Manual Registration – Setting Constructor Arguments

StructureMap Manual Registration – Setting Constructor Arguments


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

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: