Created
May 19, 2012 12:07
-
-
Save jpolvora/2730615 to your computer and use it in GitHub Desktop.
InterceptingWithDuckTyping.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace DynamicProxy.Console | |
{ | |
class Program | |
{ | |
static void Main() | |
{ | |
var myContext = new MyContext(); | |
//create entries in DbContext | |
Customer entry = myContext.Customers.FirstOrDefault(); | |
//MyContext doesn't implement IDbContext, but contains the methods of IDbContext | |
//so acts like a IDbContext | |
IDbContext duck = Impromptu.ActLike<IDbContext>(myContext); | |
IDbContext proxy = ObjectProxyFactory.CreateUsingActions(duck, | |
pre => | |
{ | |
System.Console.WriteLine("Entering \"{0}\" method from {1}", pre.CallCtx.MethodName, pre.Target); | |
}, | |
post => | |
{ | |
System.Console.WriteLine("Exiting {0} method from {1}", post.CallCtx.MethodName, post.Target); | |
}, null, false, e => e.Entry(null)); | |
var dbEntry = proxy.Entry(entry); | |
System.Console.WriteLine(dbEntry.Entity.ToString()); | |
System.Console.ReadKey(); | |
} | |
} | |
/* | |
Output of the console will be: | |
Entering "Entry" method from DynamicProxy.Console.Model.MyContext | |
Exiting Entry method from DynamicProxy.Console.Model.MyContext | |
System.Data.Entity.Infrastructure.DbEntityEntry | |
*/ | |
using System.Data.Entity.Infrastructure; | |
namespace DynamicProxy.Console.Model | |
{ | |
//DbContext from EntityFramework contains a method called Entry | |
public interface IDbContext | |
{ | |
DbEntityEntry Entry(object entry); | |
} | |
} | |
using System.Data.Entity; | |
using DynamicProxy.Console.Infra; | |
namespace DynamicProxy.Console.Model | |
{ | |
public class MyContext : DbContext | |
{ | |
public MyContext() | |
: base("MyContext") | |
{ | |
Configuration.AutoDetectChangesEnabled = false; | |
Configuration.LazyLoadingEnabled = false; | |
Configuration.ProxyCreationEnabled = false; | |
Configuration.ValidateOnSaveEnabled = false; | |
} | |
public IDbSet<Customer> Customers { get; set; } | |
public IDbSet<Order> Orders { get; set; } | |
public IDbSet<CustomerOrder> CustomerOrders { get; set; } | |
static MyContext() | |
{ | |
//Database.SetInitializer(new DropCreateDatabaseAlways<MyContext>()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment