/Fody

Extensible tool for weaving .net assemblies

Primary LanguageC#MIT LicenseMIT

AppVeyor Chat on Gitter NuGet Status Join the chat at https://gitter.im/Fody/Fody Backers on Open Collective Sponsors on Open Collective

Icon

Extensible tool for weaving .net assemblies

Introduction

Manipulating the IL of an assembly as part of a build requires a significant amount of plumbing code. This plumbing code involves knowledge of both the MSBuild and Visual Studio APIs. Fody attempts to eliminate that plumbing code through an extensible add-in model.

Support Fody

If you dont have time to contribute code via PRs the you can support financially using OpenCollective.

Usage

Install using NuGet. See Using the package manager console for more info.

Fody ships in two parts:

  1. The core "engine" shipped in the Fody NuGet package
  2. Any number of "addins" or "weavers" which are all shipped in their own NuGet packages.

The below examples will use Virtuosity.

Add the nuget

Install the package in the project:

Install-Package WeaverName.Fody

e.g.

Install-Package Virtuosity.Fody

Update Fody

Since NuGet always defaults to the oldest, and most buggy, version of any dependency it is important to do a NuGet update of Fody after installing any weaver.

Update-Package Fody

Subscribe to Fody on Libraries.io to get notified of releases of Fody.

Add FodyWeavers.xml

To indicate what weavers run and in what order a FodyWeavers.xml file is used at the project level. It needs to be added manually. It takes the following form:

<?xml version="1.0" encoding="utf-8" ?>
<Weavers>
  <WeaverName/> 
</Weavers>

e.g.

<?xml version="1.0" encoding="utf-8" ?>
<Weavers>
  <Virtuosity/> 
</Weavers>

The Project Configuration Manager provides an interactive tool that can support you configuring your weavers, which is especially helpful in solutions with many projects.

Supported Runtimes

No explicit code is in place to check for non supported versions, and throw an error. As such earlier versions of .net may work as a side effect.

Any bugs found must be reproduced in a supported version.

Downstream plugins are recommended to follow the above guidelines.

Reasons

While it may seam trivial to "implement support for earlier versions of.net" the long term support implications are too costly. For example to support earlier versions of .net require

  • Custom VMs to verify problems.
  • Added complexity to setting up build environment.
  • Bugs in unsupported versions in .NET may be manifest as bugs in Fody.

Edit and continue

Edit and continue is not supported. There is no extension point to re-weave an assembly after the edit part.

Project formats

The following are not supported

To tell the difference between the old and new csproj formats.

The old format starts with

<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

The new format starts with

<Project Sdk="Microsoft.NET.Sdk">

For all these scenarios is it instead recommended to move to the new VS 2017 SDK style projects.

References

The nuget package

https://www.nuget.org/packages/Fody/

PM> Install-Package Fody

Why?

This technique of "weaving" in new instructions is fantastically powerful. You can turn simple public properties into full INotifyPropertyChanged implementations, add checks for null arguments, add Git hashes to your Assemblies, even make all your string comparisons case insensitive.

The plumbing tasks Fody handles

  • Injection of the MSBuild task into the build pipeline
  • Resolving the location of the assembly and pdb
  • Abstracts the complexities of logging to MSBuild
  • Reads the assembly and pdb into the Mono.Cecil object model
  • Re-applying the strong name if necessary
  • Saving the assembly and pdb

Fody Uses Mono.Cecil and an add-in based approach to modifying the IL of .net assemblies at compile time.

  • No install required to build
  • No attributes required
  • No references required

Usage

See SampleUsage for an introduction on using Fody.

Naming

The name "Fody" comes from the small birds that belong to the weaver family Ploceidae.

Tools and Products Used

Samples

  • BasicFodyAddin A simple project meant to illustrate how to build an addin.
  • FodyAddinSamples is a single solution that contains a working copy of every fody addin.

Addins List

  • Anotar Simplifies logging through a static class and some IL manipulation.
  • AssertMessage Generates 'message' from sourcecode and adds it to assertion.
  • AsyncErrorHandler Integrates error handling into async and TPL code.
  • AutoDependencyProperty Generates WPF DependencyProperty boilerplate from automatic C# properties.
  • AutoProperties Gives you extended control over auto-properties, like directly accessing the backing field or intercepting getters and setters.
  • AutoDI A dependency injection container and a framework to simplify working with dependency injection (DI). It is built on top of the Microsoft.Extensions.DependencyInjection.Abstractions.
  • AutoLazy Automatically implements the double-checked locking pattern on specified properties and methods.
  • BasicFodyAddin A simple project meant to illustrate how to build an addin.
  • Bindables Converts your auto properties into Wpf dependency or attached properties. Allows specifying options, defining readonly properties, and calling property changed methods.
  • Caseless Change string comparisons to be case insensitive.
  • Catel For transforming automatic properties into Catel properties.
  • Cauldron Provides method, property and field interception. It also provides weavers for Cauldron.Core and Cauldron.Activator.
  • ConfigureAwait Allows you to set the async ConfigureAwait at a global level for all your await calls.
  • Costura For embedding references as resources.
  • CryptStr Encrypts literal strings in your .NET assemblies.
  • DependencyInjection automatic dependency injection for Ninject, Autofac and Spring.
  • EmptyConstructor Adds an empty constructor to classes even if a non empty one is defined.
  • EmptyStringGuard Adds empty string argument checks to an assembly.
  • EnableFaking Allows faking your types without writing interfaces for testing purposes only.
  • Equals Generate Equals, GetHashCode and operators methods from properties.
  • Equatable Generate Equals, GetHashCode and operators methods from explicit annotated fields and properties.
  • Expose Exposes members and optionally implements interface of a field declared in class.
  • ExtraConstraints Facilitates adding constraints for Enum and Delegate to types and methods.
  • FactoryId Simplifies the implementation of Factory Method Pattern
  • Fielder Converts public fields to public properties.
  • FodyDependencyInjection Dependency injection with Fody add-ins.
  • Freezable Implements the Freezable pattern.
  • InfoOf Provides methodof, propertyof and fieldof equivalents of typeof.
  • Ionad Replaces static method calls.
  • Janitor Simplifies the implementation of IDisposable.
  • JetBrainsAnnotations Converts all JetBrains ReSharper code annotation attributes to External Annotations.
  • LoadAssembliesOnStartup Loads references on startup by using the types in the module initializer
  • MethodBoundaryAspect Allows to decorate methods and hook into method start, method end and method exceptions (like PostSharp)
  • MethodCache Caches return values of methods decorated with a CacheAttribute.
  • MethodDecorator Decorate arbitrary methods to run code before and after invocation.
  • MethodTimer Injects method timing code.
  • ModuleInit Adds a module initializer to an assembly.
  • Mutable Make F# setters for union types and eliminate need for CLIMutable attribute for records.
  • Mvid Adds the ability to specify the assembly MVID (Module Version Id).
  • Nancy.ModelPostprocess Modify Nancy models after route execution but before serialization
  • NullGuard Adds null argument checks to an assembly
  • Obsolete Helps keep usages of ObsoleteAttribute consistent.
  • Padded Adds padding to fight the false sharing problem.
  • PropertyChanged Injects INotifyPropertyChanged code into properties.
  • PropertyChanging Injects INotifyPropertyChanging code into properties.
  • Publicize Converts non-public members to public hidden members.
  • QueryValidator Validates your DB queries during a build.
  • Realm Mobile database: a replacement for SQLite & ORMs.
  • ReactiveUI Generates ReactiveUI RaisePropertyChange notifications for properties and ObservableAsPropertyHelper properties.
  • Resourcer Simplifies reading embedded resources from an Assembly.
  • RomanticWeb Fody weaver plugin for RomanticWeb instrumentation.
  • Spring Spring constructor configuration.
  • StampSvn Stamps an assembly with SVN data.
  • StaticProxy Proxy Generator, also for .net standard / .net core (.net standard 1.0+).
  • Substitute Substitute types with other types to e.g. intercept generated code
  • SexyProxy Proxy generator with support for async patterns.
  • SwallowExceptions Swallow Exceptions in targeted methods.
  • TestFlask Records your method args and responses to replay, assert and test.
  • Throttle Easily use throttles with minimal coding
  • ToString Generate ToString method from public properties.
  • Tracer Adds trace-enter and trace-leave log entries for selected methods.
  • Undisposed Debugging tool to track down undisposed objects.
  • Usable Adds using statements for local variables that have been created, and implement IDisposable.
  • Validar Injects IDataErrorInfo or INotifyDataErrorInfo code into a class at compile time.
  • Vandelay Simplifies MEF importing\exporting.
  • Visualize Adds debugger attributes to help visualize objects.
  • Virtuosity Change all members to virtual.
  • WeakEvents Automatic publishing of weak events via compile time code weaving and a supporting runtime library.
  • With Methods to return copies of immutable objects with one property modified.
  • YALF Yet Another Logging Framework.
  • Tail Adds a postfixed method call instruction to recursive calls.

No longer maintained

The below addins are no longer maintained. Raise an issue in the specific project if you would like to take ownership.

  • ArraySlice ArraySlice allows to build shared memory array views without performance impact. It uses IL manipulation to achieve the fastest implementation.
  • Cilador Write your own mixins in C# for code reuse without inheritance.
  • Commander Injects ICommand properties and implementations for use in MVVM applications.
  • Mixins A mixin is a class that provides a certain functionality to be inherited or just reused by a subclass.
  • NameOf Provides strongly typed access to a compile-time string representing the name of a variable, field, property, method, event, enum value, or type.
  • RemoveReference Facilitates removing references in a compiled assembly during a build.
  • Scalpel Strips tests from an assembly.
  • Seal mark all non-virtual(abstract, non-sealed) types as sealed by default.
  • Stiletto Compile-time static analysis and optimization for the Stiletto IoC library.
  • Stamp Stamps an assembly with git data.

Projects built using Fody

Icon

Bird designed by Marco Hernandez from The Noun Project

More Info

With thanks to

Resharper from Jetbrains

http://www.jetbrains.com/resharper/

Resharper.png

TeamCity from Jetbrains

http://www.jetbrains.com/teamcity/

TeamCity.png

Contributors

This project exists thanks to all the people who contribute. [Contribute].

Backers

Thank you to all our backers! 🙏 [Become a backer]

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]