繁体   English   中英

如果在运行时创建实例,如何解决构造函数参数?

[英]How resolve constructor params if create instance in runtime?

我有一个工作过的天青角色,有类型列表,可以在运行时创建它。 我需要使用IoC(结构图)来初始化构造函数参数。 现在我有这个课:

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>();
        }
}

现在我创建:

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

但是我需要使用零个或多个paramas来初始化构造函数。 我的格式化人员不需要了解IContaiiner

我想要构造函数中的参数:

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

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

如果知道要使用StructureMap解析的类型,则应该能够像以下操作一样轻松地创建它:

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>();

自从我上次查看StructureMap以来已经有很长时间了,因此我对它的API的使用可能已经过时,但是一般概念应该保持不变。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM