如何动态地在StructureMap中创建对象的实例?

时间:2016-05-16 13:22:18

标签: c# abstract-class structuremap

我有一个名为" ImportRunner"。

的抽象类

我有一个名为" ScorecardRunner"。

的类的实现

当我从XML文件中将对象类型作为字符串拉回来时,我如何在运行时获取类的实例,例如ScorecardRunner,它可以是ImportRunner的任何实现?

我目前的代码如下。

var importer = container.GetInstance<ImportRunner>();

当我尝试执行类似下面的操作时,出现编译错误。

var importer = container.GetInstance<Type.GetType("Importer.ScorecardRunner")>();
  

运营商&#39;&lt;&#39;不能应用于类型&#39;方法组的操作数&#39;和   &#39;类型&#39;

谢谢,汤姆

2 个答案:

答案 0 :(得分:3)

更好的方法是创建一个负责确定正确的运行程序实例的工厂,而不是根据运行时值扩展您的逻辑以创建实例,并将其放入StructureMap的注册表中。然后注入。

例如:

public class XmlReader
{
    public bool IsScoreCard { get; set; }
}

public abstract class ImportRunner
{
}

public class ScorecardRunner : ImportRunner
{
}

public class DefaultRunner : ImportRunner
{
}

public class RunnerFactory
{
    private readonly XmlReader _reader;

    public RunnerFactory(XmlReader reader)
    {
        _reader = reader;
    }

    public ImportRunner Resolve()
    {
        if (_reader.IsScoreCard)
            return new ScorecardRunner();

        return new DefaultRunner();
    }
}

然后在注册表中配置它:

this.For<ImportRunner>().Use(ctx => ctx.GetInstance<RunnerFactory>().Resolve());

答案 1 :(得分:1)

对不起,但我不同意答案的一般断言。

如果您正在使用IoC,则不需要创建具体的工厂......这是依赖注入的全部要点。

考虑这个小例子......

  • UnitOfWork将由StructureMap实例化
  • BankAccountApplication可以&amp;也应该由StructureMap实例化

Process.BankAccounts Library - 示例类:
请注意Application类属性如何引用UnitOfWork类。

public class BankAccountApplication : IAccountApplication
{
    #region <Fields & Constants>

    private string StartingBalanceInvalidFormat = "A Starting Balance of {0} is invalid.";
    private string AnnualPercentageRateInvalidFormat = "The Annual Percentage Rate of {0} is invalid.";

    #endregion

    #region <Properties>

    [SetterProperty]
    public IDemoDbUnitOfWork UnitOfWork { get; set; }

    #endregion

    #region <Methods>

    public BankAccount CreateNew(AccountType bankAccountType, string ownerFullName, decimal startingBalance, decimal annualPercentageRate, string executedBy)
    {
        TraceHandler.TraceIn(TraceLevel.Info);

        if (string.IsNullOrWhiteSpace(ownerFullName))
            throw new ArgumentNullException("Owner Full Name");

        if (startingBalance < 0.0M)
            throw new ArgumentException(string.Format(StartingBalanceInvalidFormat, startingBalance));

        if (annualPercentageRate <= 0.0M)
            throw new ArgumentException(string.Format(AnnualPercentageRateInvalidFormat, annualPercentageRate));

        var account = new BankAccount();

        try
        {
            BankAccountType accountType = GetAccountType(bankAccountType);

            account.AnnualPercentageRate = annualPercentageRate;
            account.Balance = startingBalance;
            account.BankAccountTypeId = accountType.BankAccountTypeId;
            account.OwnerFullName = ownerFullName;
            account.ExecutedByName = executedBy;
            account.ExecutedDatetime = DateTime.UtcNow;

            UnitOfWork.BankAccounts.Add(account);
            UnitOfWork.SaveChanges();
        }
        catch (Exception ex)
        {
            TraceHandler.TraceError(ex);
        }
        finally
        {
            TraceHandler.TraceOut();
        }

        return account;
    }

    public IEnumerable<BankAccount> FindOverdrafts(IAccountAlgorithm overdraftAlgorithm)
    {
        TraceHandler.TraceIn(TraceLevel.Info);

        var accounts = new List<BankAccount>();

        try
        {
            var entities = UnitOfWork.BankAccounts.GetAll().ToList();

            entities.ForEach(e => {

                IAlgorithmResult calculation = overdraftAlgorithm.Calculate(e.Balance);

                if (calculation.Result)
                    accounts.Add(e);
            });
        }
        catch (Exception ex)
        {
            TraceHandler.TraceError(ex);
        }
        finally
        {
            TraceHandler.TraceOut();
        }

        return accounts.AsEnumerable();
    }

    private BankAccountType GetAccountType(AccountType bankAccountType)
    {
        var name = bankAccountType.ToStringValue();

        // In this case I am going to assume all accounts are properly mapped -> First()
        return UnitOfWork.BankAccountTypes.GetAll().Where(a => a.BankAccountTypeName == name).First();
    }

    #endregion
}

Process.BankAccounts Library - ContainerRegistry:
这个ContainerRegistry扫描程序集&amp; “设置”您的根接口,然后使用您的命令获得更多“明确”的指令。

public class ContainerRegistry : Registry
{
    #region <Constructors>

    public ContainerRegistry()
    {
        Scan(
            scan =>
            {
                scan.TheCallingAssembly();
                scan.WithDefaultConventions();
                scan.LookForRegistries();
                scan.AssembliesFromApplicationBaseDirectory(f => f.FullName.StartsWith("Bushido.Common", true, null));
                scan.AssembliesFromApplicationBaseDirectory(f => f.FullName.StartsWith("Bushido.Process", true, null));
                scan.AddAllTypesOf(typeof(IAccountApplication));
                scan.AddAllTypesOf(typeof(IAccountAlgorithm));
                scan.SingleImplementationsOfInterface();
            });

        ForSingletonOf(typeof(IDbContext)).Use(typeof(DemoDbContext));

        For(typeof(IDemoDbUnitOfWork)).Use(typeof(DemoDbUnitOfWork));
        For(typeof(IRepository<>)).Use(typeof(GenericRepository<>));
    }

    #endregion
}

UnitTest Library - Builder:
当然,在单元测试中,你必须模拟第三方对象。但你可以&amp;应该使用IoC来做到这一点。

    public partial class Builder
    {
        #region <Methods>

        public T CreateInstance<T>(IDemoDbUnitOfWork unitOfWork, bool byFullName = false)
        {
            if (unitOfWork == null)
                throw new ArgumentNullException("UnitOfWork");

            // Here, I am passing-in a MOCK of the UnitOfWork & "shimming" it into "T" via IoC
            var container = IoC.Initialize();
            container.Inject(typeof(IDemoDbUnitOfWork), unitOfWork);

            return container.GetInstance<T>();
        }

        public Mock<IDemoDbUnitOfWork> CreateMockUnitOfWork()
        {
            var unitOfWork = new Mock<IDemoDbUnitOfWork>();

            // DBO Tables
            var bankAccountRepository = BankAccountRepositoryBuilder.CreateMock();
            var bankAccountTypeRepository = BankAccountTypeRepositoryBuilder.CreateMock();

            unitOfWork.SetupAllProperties();

            // DBO Tables
            unitOfWork.SetupGet(x => x.BankAccounts).Returns(bankAccountRepository.Object);
            unitOfWork.SetupGet(x => x.BankAccountTypes).Returns(bankAccountTypeRepository.Object);

            return unitOfWork;
        }

        #endregion
    }

UnitTest Library - 测试:
现在,通过Builder类,您可以很好地实例化您的类。因此,你可以很好地清理单元测试。

public void BankAccountApplication_CreateNew_Invalid_StartingBalance()
{
     // -----
     // ARRANGE

     var unitOfWork = Builder.CreateMockUnitOfWork();
     var application = Builder.CreateInstance<BankAccountApplication>(unitOfWork);

     // -----
     // ACT
     var account = application.CreateNew(AccountType.Checking, "Scrooge McDuck", -100.00M, 3.00M, Builder.ExecutedBy);

     // -----
     // ASSERT

     ...put your asserts here
}