Mediator
Mediator

Reputation: 15378

How resolve constructor params if create instance in runtime?

I have azure worked role, I have list of types and I create it in runtime. I need use IoC (structuremap) to initialize constructor params. Now I have this class:

public class BuildCompletedFormatter1
    {
        private readonly IBuildService _buildService;
        private readonly IProjectService _projectService;

        public BuildCompletedFormatter(IContainer container) : base(container)
        {
            _projectService = container.GetInstance<IProjectService>();
            _buildService = container.GetInstance<IBuildService>();
        }
}

and I now create:

var type = instanse.GetType();
object instantiatedType = Activator.CreateInstance(type, container);
return instantiatedType;

But I need initialize constructor with zero or more paramas. My formatters don't need know about IContaiiner

I want have the params in constructor:

public class BuildCompletedFormatter2
        {
            private readonly IBuildService _buildService;
            private readonly IProjectService _projectService;

            public BuildCompletedFormatter(IProjectService projectService, IBuildService buildService)
            {
                _projectService = projectService;
                _buildService = buildService;
            }
    }

Upvotes: 0

Views: 214

Answers (1)

Mark Seemann
Mark Seemann

Reputation: 233150

If you know the type you want to resolve with StructureMap, you should be able to create it as easily as:

var container = new Container();
container.Configure(r => r.For<IProjectService>().Use<MyProjectService>());
container.Configure(r => r.For<IBuildService>().Use<MyBuildService>());

var fmt = container.GetInstance<BuildCompletedFormatter2>();

It's been a long time since I last looked at StructureMap, so my use of its API may be outdated, but the general concepts ought to remain the same.

Upvotes: 1

Related Questions