到目前为止,我的存储库中有以下代码:
public MyRepo(ILog logger)
{
this.Logger = logger;
var mongoUrlBuilder = new MongoUrlBuilder(ConfigurationManager.ConnectionStrings["MyContext"].ConnectionString);
this.MongoClient = new MongoClient(mongoUrlBuilder.ToMongoUrl());
this.MongoDatabase = this.MongoClient.GetDatabase("MyDB");
this.UserCollection = this.MongoDatabase.GetCollection<MyModel>("pro");
}
这就是我使用unity DI容器的方式:
var container = new UnityContainer();
container.RegisterType<IMyModel, MyModel>();
RegisterTypes(container);
return container;
如何使用unity DI来注入MongoDb?
我要问的主要原因是因为我希望能够模拟mongoDb并对其进行测试。这些要求要求我使用Unity DI和MongoDb。
更新
最终,我选择了以下内容。我添加了一个看起来像这样的Db上下文类:
public class MongoDbContext
{
public const string CONNECTION_STRING_NAME = "DBContext";
public const string DATABASE_NAME = "MyDb";
private static readonly IMongoClient Client;
private static readonly IMongoDatabase Database;
static MongoDbContext()
{
var connectionString = ConfigurationManager.ConnectionStrings[CONNECTION_STRING_NAME].ConnectionString;
Client = new MongoClient(connectionString);
Database = Client.GetDatabase(DATABASE_NAME);
}
public IMongoCollection<TEntity> GetCollection<TEntity>()
{
return Database.GetCollection<TEntity>(typeof(TEntity).Name.ToLower() + "s");
}
}
在MongoRepository中使用它:
public class MyRepository<TModel> : IGenericMongoRepository<TModel> where TModel : BaseModel
{
private MongoDbContext MongoDbContext = null;
public Exception OperationException { get; set; }
private ILog Logger;
public MyRepository(ILog logger)
{
this.Logger = logger;
this.MongoDbContext = new MongoDbContext();
}
public async Task<TModel> Add(TModel item)
{
try
{
IMongoCollection<TModel> collection = this.GetCollection<TModel>();
await collection.InsertOneAsync(item);
return item;
}
catch (Exception e)
{
}
}
}
答案 0 :(得分:1)
您可以重构repo以将mongo数据库作为可注入依赖项
private IMongoDatabase database;
private ILog Logger;
private IMongoCollection<MyModel> UserCollection;
public MyRepo(ILog logger, IMongoDatabase database) {
this.Logger = logger;
this.database = database;
this.UserCollection = database.GetCollection<MyModel>("pro");
}
然后可以将实例的创建移动到组合根
//Create the database instance
var mongoUrlBuilder = new MongoUrlBuilder(ConfigurationManager.ConnectionStrings["MyContext"].ConnectionString);
var client = new MongoClient(mongoUrlBuilder.ToMongoUrl());
var database = client.GetDatabase("MyDB");
var container = new UnityContainer();
container.RegisterType<IMyModel, MyModel>();
// Register existing object instance
container.RegisterInstance<IMongoDatabase>(database);
RegisterTypes(container);
return container;