Interpose.Core Changes

I’m writing this from the 2018 MVP Global Summit!

Got my first pull request for Interpose.Core: it came from @x2764tech and it was suggested that Interpose should target .NET Standard. For some reason, I had come to the impression that it wasn’t possible – I *had* tried – but now it seems otherwise. Also, I got a heads up that the unit tests were failing for attribute-based interception, and I now fixed it.

Interpose.Core is now at version 1.4.0. Some of the changes were:

  • BUG: fixed interception with attributes where the interception attribute was being applied at the method level, not class
  • IMPROVEMENT: targeting .NET Standard instead of .NET Core
  • IMPROVEMENT: added caching of handler instances
  • IMPROVEMENT: added support for providing a service provider
  • IMPROVEMENT: small fixes here and there

Huge thanks to x2764tech for the contribution! Winking smile

Interpose.Core Updates

Some of you may have read my previous post on Interpose.Core. I’ve made a few modifications since:

  • Added caching for type generators, meaning, you won’t have to generate the same types twice
  • Added DispatchProxy interception; if you don’t know DispatchProxy, it’s .NET Core’s replacement for RealProxy, the transparent proxy mechanism that exists in .NET “full” framework. It may be used as an alternative to interface interception, as we don’t need to generate a type at runtime

The source code is updated and so is the NuGet package. Do have a look and share your thoughts! Winking smile

Introducing Interpose.Core

Update: see this post and this one.

I’m writing this from the 2018 MVP Global Summit!

Some of you may remember a series of posts I wrote about AOP and code interception in .NET. In them I built an AOP framework from scratch that could do custom interception. A few years passed by and I decided to revisit it and turn it into a .NET Core project: I introduce to you Interpose.Core.

Interpose: place or insert between one thing and another.

Interpose is available as an open source project (under Lesser GNU Public License) which you can get from GitHub or NuGet. It can do type and instance interception:

  • Type: virtual methods, the type to intercept cannot be sealed
  • Instance: interface and dynamic interception

Interpose uses Roslyn to generate the proxy types. As it targets .NET Core, you can use it on any supported platform.

At its core, you have an interceptor class (IInstanceInterceptor or ITypeInterceptor) and you ask for an instance or a type to be intercepted using a given handler (instance or type). It then generates a proxy instance (or type, which you must instantiate yourself). When using the generated proxy instance, for the target methods or properties, it will execute the provided handler.

So, what’s an handler like? An handler is just any implementation of the IInterceptionHandler method, that offers a single method, Invoke. This method takes a parameter that describes all of the execution context (target object, target method, parameters). From it, you can run the base implementation before or after performing any actions, or you can skip it altogether, in which case, you must provide a return value yourself.

Two instance interception examples, one for each interceptor, first, interface:

var interceptor = new InterfaceInterceptor();
var instance = new MyType();
var handler = new MyHandler();
var proxy = interceptor.Intercept(instance, typeof(IMyType), handler) as IMyType;

As you can see, you need to explicitly state which interface in the target instance you wish to intercept.

For dynamic, you can do something similar:

var interceptor = new DynamicInterceptor(); var instance = new MyType(); var handler = new MyHandler(); dynamic proxy = interceptor.Intercept(instance, null, handler);

Here you don’t need to specify an interface, but you do need to declare your proxy instance as dynamic.

Types are easy to intercept too, the major difference is that you pass types, not instances:

var interceptor = new VirtualMethodInterceptor();

var proxyType = interceptor.Intercept(typeof(MyType), typeof(MyHandler));

var proxy = Activator.CreateInstance(proxyType) as MyType;

Here the handler must be a public non-abstract class with a public parameterless constructor.

A very simple handler could be:

class MyHandler : IInterceptionHandler


public void Invoke(InterceptionArgs args)


if (args.Method.ReturnType == typeof(int))


//always return 100

args.Result = 100;




Console.Out.WriteLine(“Before base method call”);


Console.Out.WriteLine(“After base method call”);




There are a couple of extensions that allow you to use a registry for mapping methods to intercept to handlers or handlers defined as attributes.

You can integrate it with .NET Core’s dependency injection framework:




Still some features missing, such as caching of generated proxy types, interception of generic types or the ability to maintain custom attributes from the base types or interfaces. Will try to address these when I have the time. Also, might be useful to have a small library of common handlers (logging, exception handling, measuring time, etc), if this ever comes to live, I will do it in a different assembly.

In the meantime, enjoy it and let me know what you think!

ASP.NET Core Pitfalls – Session Storage

Previous versions of ASP.NET featured several ways to persist sessions:

  • InProc: sessions would be stored on the server’s process memory
  • SQL Server: sessions would be serialized and stored in a SQL Server database; other vendors offered similar functionality
  • State Server: sessions would be serialized and stored on an instance of the ASP.NET State Service
  • Custom: we had to implement our own persistence mechanism

InProc was probably the most commonly used; it was the fastest, as the items in the session weren’t serialized, but on the other side they would not survive server crashes. Using this approach things usually worked well, because the session object merely provided a reference to the items stored in memory, so manipulating these items didn’t mandate that the session be explicitly saved.

In ASP.NET Core, all of this is gone. By default, sessions are still stored in memory but one can also use one of the available distributed cache mechanisms. The main difference, however, is that even when the session objects are stored in memory, they still need to be serialized and deserialized prior to persisting or retrieving them. It is no longer possible to just store a pointer to a memory object and keep manipulating it transparently; the object to be stored needs to be converted into a byte array first. You can use any serializer you want.

If we think about it seriously, it was probably a good decision: I’ve seen applications where a lot of data was being stored on the session using InProc mode, but then there was a need to switch to another mode to improve scalability, and the application would just stop working, as the objects being stored weren’t serializable. This time, we need to carefully think about it beforehand.

ASP.NET Core Pitfalls – Redirect to Action Keeps Route Parameters

When you redirect after a POST – following the famous Post-Redirect-Get pattern – but your previous view was constructed using a route parameter, then it will be sent to the redirect action as well.

For example, say you are responding to a request for /Filter/Smartphone, where Smartphone is a route parameter, you POST it to some controller action and at the end you redirect to the Index action using the RedirectToAction method:

return this.RedirectToAction(nameof(Index));

The browser will issue the GET request for Index but keeps the Smartphone route parameter, which is not good.

The solution is to pass a routeValues parameter to RedirectToAction that doesn’t contain any of the possible route parameters. One way to do it would be to create a dictionay with all action parameters nullified:

return this.RedirectToAction(nameof(Index), MethodBase.GetCurrentMethod().GetParameters().ToDictionary(x => x.Name, x => (object) null));

The solution to have this done automatically lies in the MethodBase.GetCurrentMethod() method. This way, you are sure to avoid any unwanted route parameters on your next request.

In case you are wondering, passing null, a dictionary without entries or object won’t work, the only other way is to pass an anonymous value with the parameters explicitly set to null.

Entity Framework Core Succinctly Released

My latest (and fifth) ebook for Syncfusion’s Succinctly collection is out: Entity Framework Core Succinctly! It covers Entity Framework Core 2.0 and you can download it for free – need to register first, though.

This book is inspired by my previous one on Entity Framework Code First, but quite a lot has changed.

Huge thanks to Jeff Boenig for the technical review and to Hillary Bowling, Tres Watkins and Jacqueline Bieringer of Syncfusion for all their support.

2017 in Retrospective, 2018 in Perspective

site2017 was a difficult year for me, for personal reasons. So I didn’t blog that much, to be honest.

I was renewed again as Microsoft MVP, an excellent way to start the year! Hooray! Open-mouthed smile

In 2017 my second hardcopy book, Mastering ASP.NET Core 2.0, came out. It was tough, as it is a long book, and it spread from ASP.NET Core 1.1 to 2.0, but I am generally pleased with the result. You can get it in print or ebook format.

I started, with the support from Fusion Cowork and the Aveiro development community, the Fusion/Aveiro Tech Talks here in Aveiro. We’ve had 3 sessions so far, and more are on the list.

Entity Framework Core 2 was released and I talked about it. Also posted about ASP.NET Core 2, but not as much as I would have liked to.

I also covered Postal.NET, my pet project for writing decoupled .NET standard applications.

Started writing content for Stackify, and I got two posts out: .NET Core 2.1 Release: What to Expect in 2018 and How to Call WCF Services and Create SOAP Services with ASP.NET Core. More to come! Winking smile

In early 2017 I made some prophecies about what technologies would be cool that year. Looking back, I can see that I got some of them right, others probably not. I didn’t cover R or WebAssembly, and I was happy I didn’t, as I really didn’t see much going on around them – but I may be wrong, though. I also left out Blockchain, which seems to be the next cool thing. Maybe this is the year for them!

I didn’t write a single post on ASP.NET WebForms or SharePoint; this probably means that they are dead to me. I basically only work with ASP.NET Core or .NET Standard nowadays.

I would like to resume my old classics – NHibernate pitfalls, Entity Framework pitfalls – plus MongoDB in .NET, Visual Studio tips and Java vs C#. All are in the pipeline, plus some C# language improvements and some MediatR, NHibernate and Elasticsearch too! Winking smile

Something that I’ve been working on is the list of Portuguese (meaning, written by portuguese-speaking developers or in portuguese) development sites: I would really like to keep this up to date! For this to be helpful, however, it should only contain “live” sites, those that have activity. I count on you folks to keep me posted on that! Winking smile

Anyway, thank you all for reading this blog, you’re the reason I write it! Keep dropping by and sending me your comments/questions/corrections/complaints! Smile

  • Entity Framework Core Pitfalls: No TransactionScope Support

    Entity Framework Core, as of version 2.0, does not support enlisting in ambient transactions, like those provided by TransactionScope. It is being tracked by issue #9561. This is by design and is related to a limitation of System.Data.SqlClient, which will be fixed when .NET Core 2.1 comes out. The ticket for SqlClient is #3114.

    I already talked about the hard relation between Entity Framework and TransactionScope before. This time, however, with EF Core 2.1, it seems that it will be fixed, and this is a good thing. For now, however, you will have to roll out your own transaction management strategy which includes starting your own transactions explicitly and either committing them or rolling them back at the end. Please refer to the Microsoft documentation available at

    Soft Deletes with Entity Framework Core 2 – Part 2

    My previous post explained how to setup soft deletes for queries automatically. This time, I’m going to talk about the other part: actually replacing a delete for an update that sets the is deleted column.

    The key here is to intercept the SaveChanges method, find out all entities that are ISoftDeletable and are marked for deletion and then set their IsDeleted property and change their state to be modified instead of deleted:

    public override int SaveChanges()
    foreach (var entry in this.ChangeTracker.Entries().Where(e => e.State == EntityState.Deleted))
    if (entry.Entity is ISoftDeletable)
    entry.Property(_isDeletedProperty).CurrentValue = true;
    entry.State = EntityState.Modified;

    return base.SaveChanges();
    This way Entity Framework will know what to do and just update them instead of deleting them. Next time, they won’t be loaded as they have been marked as deleted.

    Soft Deletes with Entity Framework Core 2 – Part 1

    Entity Framework Core 2, already covered here, includes a cool feature called global filters. By leveraging global filters, we can apply restrictions automatically to entities, either loaded directly or through a collection reference. If we add this to shadow properties (in the case of relational databases, columns that exist in a table but not on the POCO model), we can do pretty cool stuff.

    In this example, I am going to create a soft delete global filter to all entities in the model that implement a marker interface ISoftDeletable.

    public interface ISoftDeletable
    We just need to override the DbContext’s OnModelCreating method to automatically scan all known entities to see which implement this interface and then create the restriction automatically:
    private const string _isDeletedProperty = "IsDeleted";
    private static readonly MethodInfo _propertyMethod = typeof(EF).GetMethod(nameof(EF.Property), BindingFlags.Static | BindingFlags.Public).MakeGenericMethod(typeof(bool));

    private static LambdaExpression GetIsDeletedRestriction(Type type)
    var parm = Expression.Parameter(type, "it");
    var prop = Expression.Call(_propertyMethod, parm, Expression.Constant(_isDeletedProperty));
    var condition = Expression.MakeBinary(ExpressionType.Equal, prop, Expression.Constant(false));
    var lambda = Expression.Lambda(condition, parm);
    return lambda;

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    foreach (var entity in modelBuilder.Model.GetEntityTypes())
    if (typeof(ISoftDeletable).IsAssignableFrom(entity.ClrType) == true)
    entity.AddProperty(_isDeletedProperty, typeof(bool));


    So, for each entity known from the context we add a shadow property called IsDeleted of type bool. Of course, needless to say, it must also exist on the database. The reason I’m making it a shadow property is to avoid people tampering with the entities, by setting or unsetting its value. This way, the restriction is always performed and it is invisible to us. After we create the property, we add a restriction to the entity’s type.
    Simple, don’t you think? This way, if you want to enable or disable it for a number of entities, just have them implement the ISoftDeletable interface.