实现 MongoDB Repository in C# using Ninject

10/12/2018 .NETMongoDB后端

首发于个人博客 CoderMiner技术博客 在 ASP.NET Web Api工程中没有关于MongoDB相关的框架,封装一下访问MongoDB的操作,public class IEntity{ [BsonId] public string id { get; set; }

**首发于个人博客 CoderMiner技术博客 (opens new window) **

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

public class IEntity
{
    [BsonId]
    public string id { get; set; }
    public long date { get; set; }
}
1
2
3
4
5
6

# 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);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# 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);
}
1
2
3
4
5
6
7
8
9
10

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


}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

# 特定Document的封装

IUserRepository.cs

public interface IUserRepository : IMongoRepository<UserModel>
{
}
1
2
3

UserRepository.cs

public class UserRepository : MongoRepository<UserModel>,IUserRepository
{
    public UserRepository(string connection) : base(connection)
    {
    }
}
1
2
3
4
5
6

# Service封装

IUserService.cs

public interface IUserService
{
    void Register(UserModel model);
    IEnumerable<UserModel> GetAllUsers();
}
1
2
3
4
5

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);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

#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());
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# 使用Ninject实现依赖注入

通过nuget安装Ninject相关的包

Ninject.Web.Common.WebHost
Ninject.Web.WebApi
1
2

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

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

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

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

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

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

更多精彩内容 (opens new window)
源码 (opens new window)