如何使用简单的注入器

时间:2015-12-10 22:41:39

标签: c# .net dependency-injection simple-injector

我是简单注射器的新手。我有数据访问层,它依赖于Force Client。我已经注册了ForceClient依赖项。我想在用户登录应用程序后替换默认值ForceClient

请告诉我,如何在运行时更改默认值。

Ioc.ServiceContainer.Register(() => new ForceClient(
    "test",
    "test",
    "test"));

以下是有关要求的完整详细信息。我在Xamarin项目中使用DAL,使用Developerforce.Force apis从销售人员中检索数据。我正在使用MOQ编写单元测试用例来测试DAL。

DAL代码。

public CustomerRepository(IForceClient client)
{
    _client = client;                       
}

public async Task<long> GetTotalContacts()
{
    string totalContactCountQry = "some query"

    var customerCount =  await _client.QueryAsync<ContactsTotal>(totalContactCountQry);
    var firstOrDefault = customerCount.Records.FirstOrDefault();

    return firstOrDefault != null ? firstOrDefault.Total : 0;
}

单元测试用例代码。

[SetUp]
public void Init()
{
    forceClientMock = new Mock<IForceClient>();
    forceClientMock.Setup(x => x.ForceClient(It.IsAny<string>(), 
        It.IsAny<string>(), It.IsAny<string>(), It.IsAny<HttpClient>()))
        .Return(new ForceClient(It.IsAny<string>(), It.IsAny<string>(), 
            It.IsAny<string>(), It.IsAny<HttpClient>()));              
    forceClientMock.Setup(x => x.QueryAsync<ContactsTotal>(It.IsAny<string>()))
        .ReturnsAsync(new QueryResult<ContactsTotal>());
    forceClientMock.Setup(x => x.QueryAsync<ContactsTotal>(It.IsAny<string>()))
        .ReturnsAsync(new QueryResult<ContactsTotal>() { Records=new List<ContactsTotal>() });            
}

[Test]
public void GetTotalContacts()
{              
    ICustomerRepository customerRepostory = new CustomerRepository(forceClientMock.Object);
    Assert.AreEqual(customerRepostory.GetTotalContacts().Result,0);
}

应用程序初始化时的简单注入器注册表

container.Register<IForceClient>((() => new ForceClient(
    UserState.Current.ApiBaseUrl,
    UserState.Current.AuthToken.AccessToken,
    UserState.Current.ApiVersion)), Lifestyle.Transient);

我正在使用默认值UserState创建我在注册表中创建的ForceClient实例。一旦用户登录到应用程序,就会分配实际值。

我除了ForceClient实例在登录后拥有更新的值以访问销售人员以检索数据但程序在DAL行下面给出错误

var customerCount =  await _client.QueryAsync<ContactsTotal>(totalContactCountQry);

原因是forceClient仍然包含默认值。如何确保在登录后创建FoceClient实例以使用UserState的实际值

1 个答案:

答案 0 :(得分:1)

您可以使用Func<T>完成您想要的任务。

您可以注入IForceClient

而不是Func<IForceClient>
public CustomerRepository(Func<IForceClient> clientFunc)
{
    _clientFunc = clientFunc;
}

public async Task<long> GetTotalContacts()
{
    string totalContactCountQry = "some query"

    // calling _clientFunc() will provide you a new instance of IForceClient
    var customerCount =  await _clientFunc().QueryAsync<ContactsTotal>(totalContactCountQry);
    var firstOrDefault = customerCount.Records.FirstOrDefault();

    return firstOrDefault != null ? firstOrDefault.Total : 0;
}

简单的注射器注册:

// Your function
Func<IForceClient> fonceClientFunc = () => new ForceClient(
    UserState.Current.ApiBaseUrl,
    UserState.Current.AuthToken.AccessToken,
    UserState.Current.ApiVersion);

// the registration
container.Register<Func<IForceClient>>( () => fonceClientFunc, Lifestyle.Transient);