实现 MongoDB Repository in C# using Ninject

首发于个人博客 CoderMiner技术博客

ASP.NET Web Api工程中没有关于MongoDB相关的框架,封装一下访问MongoDB的操作,

public class IEntity
{
    [BsonId]
    public string id { get; set; }
    public long date { get; set; }
}

MongodbContext

public class MongodbContext
{
    private  IMongoDatabase database;
    private  IMongoClient client;
    private static MongodbContext context;
    private MongodbContext() { }

    public static MongodbContext Create(string connection)
    {
        if(context == null)
        {
            context = new MongodbContext();
            var url = MongoUrl.Create(connection);
            context.client = new MongoClient(url);
            context.database = context.client.GetDatabase(url.DatabaseName);
        }
        return context;
    }

    public IMongoCollection<T> GetCollection<T>()
    {
        return context.database.GetCollection<T>(typeof(T).Name);
    }
}

IMongoRepository 接口和实现 MongoRepository

IMongoRepository.cs

public interface IMongoRepository<T> where T : IEntity
{
    void Insert(T item);
    void InsertMany(IEnumerable<T> items);
    IEnumerable<T> GetAll();
    T GetOne(string id);
    bool Update(T item);

    bool Delete(string id);
}

MongoRepository.cs

public class MongoRepository<T> : IMongoRepository<T> where T : IEntity
{
    private MongodbContext _context;
    public MongoRepository(string connection)
    {
        _context = MongodbContext.Create(connection);
    }
    public bool Delete(string id)
    {
        var filter = Builders<T>.Filter.Eq(m => m.id, id);
        var result = _context.GetCollection<T>().DeleteOne(filter);
        return result.DeletedCount > 0;
    }

    public IEnumerable<T> GetAll()
    {
        var filter = Builders<T>.Filter.Empty;
        return _context.GetCollection<T>().Find(filter).ToList();
    }

    public T GetOne(string id)
    {
        var filter = Builders<T>.Filter.Eq(m => m.id, id);
        return _context.GetCollection<T>().Find(filter).FirstOrDefault();
    }

    public void Insert(T item)
    {
        item.id = ObjectId.GenerateNewId(DateTime.Now).ToString();
        _context.GetCollection<T>().InsertOne(item);
    }

    public void InsertMany(IEnumerable<T> items)
    {
        _context.GetCollection<T>().InsertMany(items);
    }

    public bool Update(T item)
    {
        var filter = Builders<T>.Filter.Eq(m => m.id, item.id);
        var result = _context.GetCollection<T>().ReplaceOne(filter, item);
        return result.ModifiedCount > 0;
    }


}

特定Document的封装

IUserRepository.cs

public interface IUserRepository : IMongoRepository<UserModel>
{
}

UserRepository.cs

public class UserRepository : MongoRepository<UserModel>,IUserRepository
{
    public UserRepository(string connection) : base(connection)
    {
    }
}

Service封装

IUserService.cs

public interface IUserService
{
    void Register(UserModel model);
    IEnumerable<UserModel> GetAllUsers();
}

UserService.cs

public class UserService : IUserService
{
    private IUserRepository _userRepository;
    public UserService(IUserRepository userRepository)
    {
        _userRepository = userRepository;
    }

    public IEnumerable<UserModel> GetAllUsers()
    {
        return _userRepository.GetAll();
    }

    public void Register(UserModel model)
    {
        _userRepository.Insert(model);
    }
}

Controller中使用示例

public class UserController : ApiController
{
    private IUserService _userService;
    public UserController(IUserService userService)
    {
        _userService = userService;
    }


    public IHttpActionResult Post([FromBody] UserModel model)
    {
        _userService.Register(model);
        return Ok(model);
    }


    public IHttpActionResult Get()
    {
        return Ok(_userService.GetAllUsers());
    }
}

使用Ninject实现依赖注入

通过nuget安装Ninject相关的包

Ninject.Web.Common.WebHost
Ninject.Web.WebApi

安装完成之后,会在App_Start文件夹中自动生成一个 Ninject.Web.Common.cs,在方法 CreateKernel中添加下面一行

RegisterServices(kernel);
GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
return kernel;

在方法RegisterServices中,绑定相关的接口和示例

kernel.Bind<IUserService>().To<UserService>();
kernel.Bind<IUserRepository>().To<UserRepository>().WithConstructorArgument("connection", REPODB);

Web.config 中配置 MongoDB 的连接字符串

<appSettings>
  <add key="TestDB" value="mongodb://127.0.0.1:27017/TestDB"/>
</appSettings>

更多精彩内容
源码