我的来源是https://github.com/tonyeung/generic-repo
我想创建一个可以在不同项目中引用的通用存储库。我见过的大多数通用存储库实现都很难。我偶然发现http://blog.damianbrady.com.au/2012/07/24/a-generic-repository-and-unit-of-work-implementation-for-entity-framework/,发现它对我的想法很有用。我的每个项目都可以在其中定义一个上下文,然后我只需要引用一个通用的存储库项目或dll并传入上下文,我就准备好了。
我唯一想弄清楚的是如何连接结构图,因为有一些需要解决的嵌套依赖项。不幸的是,博客并没有真正解决如何使用通用存储库实现依赖注入。我试图修改实现(参见上面引用的git hub repo),但是在配置结构图时我做错了。
依赖关系的工作原理如下: 存储库在构造函数中获取上下文,然后上下文依次获取连接字符串。构造函数参数是与IType映射的默认约定匹配的所有接口。我的假设是,由于我有自动注册,我需要做的就是明确定义上下文的注册,告诉structuremap它应该从app.config获取连接字符串,我应该好好去。
然而,结构图无法像我想象的那样计算出注册:
StructureMap Exception Code: 202
No Default Instance defined for PluginFamily Generic_Repository_Test.IGenericRepository`1
[[ViewModel.Customer, ViewModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]],
Generic Repository Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
注册码
//This is commented out since it should not be necessary.
//I tried to put this in for grins
//and see if it would resolve the issue but it doesn't.
//For<IGenericRepository<Customer>>().Use<GenericRepository<CustomerContext, Customer>>();
For<ICustomerContext>()
.Use<CustomerContext>()
.Ctor<string>("connectionString")
.EqualToAppSetting("ConnectionString");
//I've tried moving scan to the top but it didn't make a difference
Scan(x =>
{
x.AssembliesFromApplicationBaseDirectory();
x.WithDefaultConventions();
});
答案 0 :(得分:0)
实际上问题确实是一个配置问题。 问题是app.settings connectionstring设置返回null,我不知道为什么会发生这种情况,但我只为grins硬编码连接字符串。稍后会知道这个问题。
解决后,我仍然需要手动配置repo和上下文,因为弹出了另一个错误。
解决后,看起来结构图试图自行解决,所以我不得不添加命名空间排除。
完成的代码如下所示:
public class DependencyRegistry : Registry
{
public DependencyRegistry()
{
For<ICustomerContext>()
.Use<CustomerContext>()
.Ctor<string>("connectionString")
//.EqualToAppSetting("ConnectionString");
.Is(@"Data Source=(localdb)\Projects;Initial Catalog=EventStorage;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False");
For<IGenericRepository<Customer>>().Use<GenericRepository<ICustomerContext, Customer>>();
Scan(x =>
{
x.AssembliesFromApplicationBaseDirectory();
x.ExcludeNamespace("StructureMap");
x.WithDefaultConventions();
});
}
}