c# - 使用 Ninject 传递构造函数

标签 c# asp.net-mvc ninject

我有一个基本通用存储库和许多从基本存储库继承的类存储库。我也需要将字符串值传递给通用存储库。

这是我的通用存储库

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);

}

我的类(class)库

public class MarketRepository : Repository<Market>, IMarketRepository
    {

    }

和界面

public interface IMarketRepository : IRepository<Market>
{

}

现在我想将 sessionId 传递给通用存储库构造函数。 我怎样才能做到这一点。在这种情况下,我必须在每个类存储库中实现一个构造函数并将其传递给基础存储库。而且接口(interface)甚至不知道该构造函数。

这是 Ninject 绑定(bind)

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>();
}  

最佳答案

您可以将其添加到绑定(bind)中:

Bind<IMarketRepository>().To<MarketRepository>().WithConstructorArgument("sessionId", "Session ID here");

关于c# - 使用 Ninject 传递构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14614814/

相关文章:

C# Entity Framework (代码优先),在模型上实现 CRUD 操作

ninject - 是否可以将 Ninject Factory Extensions 的 ToFactory 方法与开放泛型一起使用?

ninject - 我有哪些选项可以使用 NInject 自动绑定(bind)

c# - System.Drawing.Color 与 TypeNameHandling 的 JSON.NET 序列化

c# - 即使条件评估为 false,If 语句似乎也在评估

c# - 实例中的静态方法

c# - 如何关闭 this.form

asp.net-mvc - 验证 mvc 页面中隐藏字段的最佳方法是什么?

asp.net-mvc - ASP.NET MVC 模型绑定(bind)和验证顺序

delegates - 使用 Ninject 进行惰性泛型委托(delegate)初始化