2016-03-15 31 views
0

我有一個自定義的DbContext它的名字是的DbContext(https://github.com/bilal-fazlani/tracker-enabled-dbcontext)。我想用它來做審計日誌我如何可以使用自定義的DbContext(審計日誌)與sharprepository

我怎樣才能實現EFRepository啓用跟蹤,?

我實現了跟蹤器啓用上下文,但我無法解決如何覆蓋尖銳回購提交方法。

public class HayEntities : TrackerContext 
    { 
    static HayEntities() 
    { 
     Database.SetInitializer<HayEntities>(null); 
    } 
    public HayEntities() : base(HayEntities) 
    { 
     this.Configuration.ProxyCreationEnabled = false; 
     this.Configuration.LazyLoadingEnabled = true; 
     this.Configuration.ValidateOnSaveEnabled = false; 
    } 
    public DbSet<Dummy> Dummys{ get; set; } 
    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     modelBuilder.Configurations.Add(new DummyConfiguration()); 

    } } 
    } 
public class DummyRepository : ConfigurationBasedRepository<DE.Dummy, long>, IDummyRepository 
    { 
     private readonly IRepository<DE.Dummy, long> _servisHasarRepository; 
     public DummyRepository (HayEntities hayEntities, ICachingStrategy<DE.Dummy, long> cachingStrategy = null) 
     {this.CachingEnabled = false; 
      _dummyRepository = new EfRepository<DE.Dummy, long>(hayEntities, cachingStrategy); 
     } 
public void UpdateOrCreate() { 
//In this area how can override save/commit method 
} 
    } 
+0

嗨。你能告訴我們你到目前爲止所嘗試過的,所以我們可以幫助你。 –

回答

0

您將要告訴SharpRepository使用IoC提供程序來注入DbContext。這將負責爲您的EfRepository獲取正確的DbContext。

如果您想根據配置控制事物並擁有自定義存儲庫,以便您可以實現自己的方法(如UpdateOrCreate()),那麼您將繼承ConfigurationBasedRepository,就像您在示例中一樣。

有上設置IoC和SharpRepository這裏更多的細節:http://fairwaytech.com/2013/02/sharprepository-configuration/(看在「實體框架和共享的DbContext」一節)

上的NuGet首先尋找SharpRepository.Ioc *找到特定的IoC您正在使用。如果你正在使用StructureMap,那麼你會做這樣的事情。

在你StructureMap配置:

// Hybrid (once per thread or ASP.NET request if you’re in a web application) 
For<DbContext>() 
    .HybridHttpOrThreadLocalScoped() 
    .Use<HayEntities>() 
    .Ctor<string>("connectionString").Is(entityConnectionString); 

然後,你需要通過調用你的啓動代碼告訴SharpRepository使用StructureMap:

RepositoryDependencyResolver.SetDependencyResolver(new StructureMapDependencyResolver(ObjectFactory.Container)); 

做這些事以後,這時如果使用EfRepository那麼它會知道要向StructureMap提供DbContext。

現在在上面你使用ConfigurationBasedRepository的例子中,我建議在配置文件中設置緩存而不是在代碼中,因爲你使用配置來加載存儲庫。由於IoC正在處理DbContext,因此您不需要執行任何操作,您可以專注於要編寫的自定義方法。

public class DummyRepository : ConfigurationBasedRepository<DE.Dummy, long>, IDummyRepository 
{ 
    public void UpdateOrCreate() 
    { 
     // You have access to the underlying IRepository<> which is going to be an EfRepository in your case assuming you did that in the config file 
     // here you can call Repository.Add(), or Reposiory.Find(), etc. 
    } 
} 
+0

謝謝。但是你有沒有SimpleInjector的例子? – muhammetsahin

+0

有一個SimpleInjector nuget包,您可以以類似的方式使用StructureMap:http://www.nuget.org/packages/SharpRepository.Ioc.SimpleInjector/ –