1

1つの基本汎用リポジトリと、基本リポジトリから継承する多くのクラスリポジトリがあります。文字列値を汎用リポジトリに渡す必要があります。

これが私の汎用リポジトリです

public class Repository<T> where T : EntityBase
    {
        private string SessionId;

        public Repository(string sessionId)
        {
            this.SessionId = sessionId;
        }

        protected virtual IDbConnection GetCn()
        {
            return new SqlConnection(ConfigurationManager.ConnectionStrings["SalesDb"].ConnectionString);
        }

        public virtual int Insert(T entity)
        {
            entity.ChUser = "anders.persson";
            entity.ChTime = DateTime.Now;

            using (IDbConnection cn = GetCn())
            {
                cn.Open();

                return cn.Insert(entity);
            }
        }

        // MORE CODE
        }
    }

そしてインターフェース

public interface IRepository<T>
{
    int Insert(T entity);

}

マイクラスリポジトリ

public class MarketRepository : Repository<Market>, IMarketRepository
    {

    }

そしてインターフェース

public interface IMarketRepository : IRepository<Market>
{

}

次に、sessionIdをGenericRepositoriesコンストラクターに渡します。どうやってやるの。この場合、すべてのクラスリポジトリにコンストラクタを実装し、それをベースリポジトリに渡す必要があります。そして、インターフェースはそのコンストラクターについてさえ知りません。

これがNinjectバインディングです

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind(typeof(IRepository<>)).To(typeof(Repository<>));
    kernel.Bind<ILeadRepository>().To<LeadRepository>();
    kernel.Bind<IPricelistRepository>().To<PricelistRepository>();
    kernel.Bind<IOptionalGroupRepository>().To<OptionalGroupRepository>();
    kernel.Bind<IProductGroupRepository>().To<ProductGroupRepository>();
    kernel.Bind<IProductRepository>().To<ProductRepository>();
    kernel.Bind<IMarketRepository>().To<MarketRepository>();
    kernel.Bind<IModelRepository>().To<ModelRepository>();
    kernel.Bind<IOrderRepository>().To<OrderRepository>();
}  
4

2 に答える 2

2

バインディングに追加できます:

Bind<IMarketRepository>().To<MarketRepository>().WithConstructorArgument("sessionId", "Session ID here");
于 2013-01-30T22:31:43.713 に答える
2

これsessionIdはランタイム値になるため、解決時に ctor に渡す必要があります。
これを行う構文は次のとおりです。

var reposetory 
    = kernel.Get<IMarketRepository>(new ConstructorArgument("sessionId", sessionId));

Service Locatorを使用せずに直接呼び出しGet、代わりに ctor インジェクションを使用する場合は、それをファクトリ内にカプセル化できます。

構成:

kernel.Bind<IRepositoryFactory>().To<RepositoryFactory>()
      .WithConstructorArgument("kernel", kernel);

工場:

public class RepositoryFactory : IRepositoryFactory
{
    private IKernel _kernel;

    public RepositoryFactory(IKernel kernel)
    {
        _kernel = kernel;
    }

    public T CreateNew<T>(string sessionId)
    {
        return
            _kernel.Get<T>(new ConstructorArgument("sessionId", sessionId));
    }
}

使用法:

var repository = _repositoryFactory.CreateNew<IMarketRepository>(sessionId);
于 2013-01-30T22:28:29.063 に答える