How to apply Serializable attribute globally?

Viewed 377

I have to apply [Serializable()] attribute for all classes, but I want to know is there any way to make classes Serializable globally instead of applying this attribute individually for all classes?

1 Answers

No, there isn't a way of applying this globally - you'd have to visit each type and add the attribute.

However: applying this globally is a really, really bad idea. Knowing exactly what you're serializing, when, and why is really important - whether this is for session-state, primary persistence, cache, or any other use-case. Statements like

I have to apply [Serializable()] attribute for all classes

tells me that you are not currently in control of what you are storing.

Additionally, since [Serializable] maps (usually) to BinaryFormatter, it is important to know that there are a lot of ways (when using BinaryFormatter) in which it is possible to accidentally drag unexpected parts of your model into the serialized data. The most notorious of these is "events", but: there are others.

When I see this type of question, what I envisage is that you're using types from your main data model as the thing that you are putting into session-state, but frankly: this is a mistake - and leads to questions like this. Instead, the far more maneagable approach is to create a separate model that exists purely for this purpose:

  • it only has the data that you need to have available in session
  • it is marked [Serializable] if your provider needs that - or whatever other metadata is needed for the sole purpose for which it exists
  • it does not have any events
  • it doesn't involve any tooling like ORM contexts, database connections etc
  • ideally it is immutable (to avoid confusion over what happens if you make changes locally, which can otherwise sometimes behave differently for in-memory vs persisted storage)
  • just plain simple basic objects - very easy to reason about
  • can be iterated separately to your main domain objects, so you don't have any unexpected breaks because you changed something innocent-looking in your domain model and it broke the serializer
Related