通过结构图进行这种注册有什么问题吗?
static public class ContainerBootstrapper
{
static public void BootstrapDefaultContainer(bool test = false)
{
StructureMap.ObjectFactory.Initialize(x =>
{
x.Scan(p =>
{
p.AssemblyContainingType<IPropertyType>();
p.AddAllTypesOf<IPropertyType>();
// p.AddAllTypesOf<IPropertyType>().NameBy(c => c.Name);
});
});
}
public interface IPropertyType : IIdentityObject, IPriority
{
string PropertyName { get; set; }
ObjectType ObjectType { get; }
string DisplayName { get; set; }
IEntityType EntityType { get; set; }
IList<IPropertyRuleObject> RuleObjects { get; set; }
void AddRuleObject(IPropertyRuleObject ruleObject);
}
public abstract class PropertyTypeBase : PersistentObject, IPropertyType
{
public PropertyTypeBase()
{
}
public PropertyTypeBase(string propertyName, string displayName)
{
PropertyName = propertyName;
DisplayName = displayName;
}
....
}
public class StringType : PropertyTypeBase
{
private ObjectType _objectType;
public StringType()
{
_objectType = new ObjectType(typeof(string));
}
public StringType(string propertyName, string displayName)
: base()
{
PropertyName = propertyName;
DisplayName = displayName;
}
public override ObjectType ObjectType
{
get { return _objectType; }
}
}
当ContainerBootstrapper.BootstrapDefaultContainer();执行我看到这行错误:
StructureMap Exception Code: 200
无法为PluginType找到名为“StringType”的实例Azarakhsh.Domain.Core.AdaptiveObjectModel.Interface.IPropertyType
主叫代码:
public IPropertyType GetPropertyType(IIdentityObject identityObject, string name)
{
string[] Properties = name.Split('.');
object Result = identityObject;
foreach (var Property in Properties)
Result = Result.GetType().GetProperty(Property).PropertyType.Name;
IPropertyType propertyType = StructureMap.ObjectFactory.GetNamedInstance<IPropertyType> (Result + "Type");
if (propertyType==null)
throw new Exception("Property type not found");
return propertyType;
}
问题是什么?
答案 0 :(得分:2)
您正在尝试获取命名实例,但从我所看到的您提供的代码中,您不会命名您的实例。为您的实例命名的代码行已注释掉。
但即使你只是在这里使用ObjectFactory.GetInstance<IPropertyType>();
,你也会遇到错误,因为structuremap不知道要使用什么构造函数。这个问题有几个解决方案。
[DefaultConstructor]
属性标记您的默认构造函数,然后它将起作用。您可以使用objectFactory手动注册它:
。x.For()使用()构造函数( “PROPERTYNAME”)是否( “someValue中”)CTOR( “显示名”)是( “someValue中”);。。
您可以按照here