带参数

时间:2015-10-26 18:16:42

标签: c# .net simple-injector

我正在尝试注册具有IDbConnection作为构造函数参数的存储库类。

public class Repository<TEntity> : IRepositoryAsync<TEntity> where TEntity : class
{
    public Repository(IDbConnection connection)
    {
        Connection = connection;
    }

    public IDbConnection Connection { get; }
}

我注册了类似的东西

var container = new Container();
container.Options.DefaultScopedLifestyle = new WcfOperationLifestyle();
container.Register(typeof(IRepositoryAsync<>), typeof(Repository<>));
container.Register(typeof(IDbConnection), typeof(Repository<User>));
    container.Register<IAuthService, AuthService>();
container.Verify();

我的代码出了什么问题?

更新 我得到如下的例外

  

Repository类型的构造函数包含带名称的参数   'connection'并键入未注册的IDbConnection。请   确保注册IDbConnection,或更改构造函数   库中。

更新2

  

[ArgumentException:提供的类型Repository未实现   IDbConnection.Parameter name:implementationType]
  SimpleInjector.Requires.ThrowSuppliedTypeDoesNotInheritFromOrImplement(类型   service,Type implementation,String paramName)+63
  SimpleInjector.Requires.ServiceIsAssignableFromImplementation(类型   service,Type implementation,String paramName)+47
  SimpleInjector.Container.Register(输入serviceType,Type   implementationType,Lifestyle生活方式,String serviceTypeParamName,   String implementationTypeParamName)+159
  SimpleInjector.Container.Register(输入serviceType,Type   implementationType)+52
  TimeTrackerService.Service.DependencyConfig..cctor()in   d:\时间跟踪\ TimeTrackerService \库\ TimeTrackerService.Service \ DependencyConfig.cs:47 [TypeInitializationException:   'TimeTrackerService.Service.DependencyConfig'的类型初始值设定项   抛出异常。]
  TimeTrackerService.Service.DependencyConfig.get_Container()in   d:\时间跟踪\ TimeTrackerService \库\ TimeTrackerService.Service \ DependencyConfig.cs:40   TimeTrackerService.WcfServiceFactory.CreateServiceHost(类型   serviceType,Uri [] baseAddresses)in   d:\时间跟踪\ TimeTrackerService \ TimeTrackerService \ WcfServiceFactory.cs:15   System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(字符串   constructorString,Uri [] baseAddresses)+524
  System.ServiceModel.HostingManager.CreateService(字符串   normalizedVirtualPath,EventTraceActivity eventTraceActivity)+1420
  System.ServiceModel.HostingManager.ActivateService(ServiceActivationInfo   serviceActivationInfo,EventTraceActivity eventTraceActivity)+52
  System.ServiceModel.HostingManager.EnsureServiceAvailable(字符串   normalizedVirtualPath,EventTraceActivity eventTraceActivity)   +641 [ServiceActivationException:由于编译期间发生异常,无法激活服务'/TrackerService.svc'。该   异常消息是:类型初始化器   'TimeTrackerService.Service.DependencyConfig'抛出异常..]
  System.Runtime.AsyncResult.End(IAsyncResult result)+489035
  System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult的   结果)+174
  System.ServiceModel.Activation.ServiceHttpModule.EndProcessRequest(IAsyncResult的   ar)+350322
  System.Web.AsyncEventExecutionStep.OnAsyncEventCompletion(IAsyncResult的   ar)+9747521

2 个答案:

答案 0 :(得分:2)

最后我提出了解决方案。而不是注入IDbConnection我注入自己的接口与实现。 IDataFactoryDataFactory。此实现返回IDbConnection

private readonly string _providerName;
private readonly DbProviderFactory _provider;
public string ConnectionString { get; set; }

public DataFactory()
{
    var con = ConfigurationManager.ConnectionStrings["TrackerConnection"];
    if (con == null)
        throw new Exception("Failed to find connection");
    ConnectionString = con.ConnectionString;
    _providerName = con.ProviderName;
    _provider = DbProviderFactories.GetFactory(con.ProviderName);
}
public IDbConnection Connection
{
    get
    {
        var connection = _provider.CreateConnection();
        if (connection == null)
            throw new Exception($"Failed to create a connection using the connection string named '{_providerName}' in app.config or web.config.");
        connection.ConnectionString = ConnectionString;
        return connection;
    }
}

然后我注册了

container.Register<IDataFactory, DataFactory>();

现在我注入我的实现

public class Repository<TEntity> : IRepositoryAsync<TEntity> where TEntity : class
{
    public Repository(IDataFactory factory)
    {
        Factory= factory;
    }

    public IDataFactory Factory{ get; }
}

现在,当我使用Factory.Connection时,它按预期工作

感谢

答案 1 :(得分:1)

另一种方式,避免添加自己的界面和实现 将此覆盖用于Register方法:
Container.Register<TService>(Func<TService> instanceCreator, Lifestyle lifestyle)

这样的事情:

container.Register<IDbConnection>(() =>{ 
    var con = ConfigurationManager.ConnectionStrings["TrackerConnection"]; 
    if (con == null) 
        throw new Exception("Failed to find connection"); 

    var _provider = DbProviderFactories.GetFactory(con.ProviderName); 

    var connection = _provider.CreateConnection(); 
    if (connection == null) 
        throw new Exception($"Failed to create a connection using the connection string named '{con.ProviderName}' in app.config or web.config."); 

    connection.ConnectionString = con.ConnectionString; 
    return connection; 
});