-1

One of the practices I adopted when I first started writing ASP.NET applications was to put the [Serializable] attribute on all model/DTO classes I wrote. The reason is because if the class was serialized into a Session or Cache object, this attribute would make sure the object serialized correctly.

I was burned early on when I didn't use the [Serializable] attribute because our development environments used InProc Sessions (single server), so the Serializable issues didn't surface until the web apps were deployed to a production web farm that used Out-of-Process Session State. In other words, the serialization errors would only crop up in production.

What I'm wondering if it is still the best practice to use the [Serializable] attribute for all model/DTO classes. There are some side effects using with ASP.NET MVC and Web API apps. Such as dealing with backing fields. There are options to remove the backing field prefixes. Unfortunately this breaks the auto property mapping when forms are posted back in MVC because properties don't contain the backing fields prefix.

Community
  • 1
  • 1
Josh
  • 8,219
  • 13
  • 76
  • 123
  • It entirely depends on what library is doing the Serialization. So I'd say not only is it not the best practice to do, it's a code smell to decorate all your DTOs with the attribute until you explicitly need it. – Rob Jan 05 '16 at 05:50

2 Answers2

1

In order to detect serialization failures use out of proc session storage even in a dev environment. This is easy to set up thanks to the session state service.

When you make something [Serializable] that restricts what you can do in that class. For example you might not want to hold onto big object graphs. Opt-in serialization seems like a safer choice. Serialization is quite dangerous and brittle.

usr
  • 168,620
  • 35
  • 240
  • 369
  • For all domain and DTO objects it makes that they support serialization, but you have a valid point that it not be a best practice to use the Serializable attribute by default. – Josh Jan 05 '16 at 00:57
0

Unfortunately this breaks the auto property mapping when forms are posted back in MVC because properties don't contain the backing fields prefix

Are you sure the binding is not working for this reason?

Anyway I usually do not use [serializable] because is not required by MVC/web.api

Martino Bordin
  • 1,412
  • 1
  • 14
  • 29
  • Yes, I ended up having to manually map properties in MVC. – Josh Jan 05 '16 at 00:46
  • I have my DTO and domain model objects in other projects, so that they can be reused. I use them in non-web projects such as console apps and Windows Services. – Josh Jan 05 '16 at 00:53
  • I just tried with Mvc 5.2.3.0 and the binding seems to work with the a [Serializable] dto – Martino Bordin Jan 05 '16 at 07:41