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

本文关键字:何解析 构造函数 参数 实例 运行时 创建 如果 | 更新日期: 2023-09-27 18:32:37

我有 azure 工作角色,我有类型列表,我在运行时创建它。我需要使用 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;

但是我需要用零个或多个参数初始化构造函数。我的格式化程序不需要了解 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的使用可能已经过时了,但一般概念应该保持不变。