Skip to content

Instantly share code, notes, and snippets.

@warrenbuckley
Last active April 18, 2019 15:48
Show Gist options
  • Save warrenbuckley/e33e4b53f3650ef34beba2fec8cbb3dd to your computer and use it in GitHub Desktop.
Save warrenbuckley/e33e4b53f3650ef34beba2fec8cbb3dd to your computer and use it in GitHub Desktop.
An example of using Umbraco CMS V8 - Collections & Type Scanning or Adding Explicit Types
using System.Collections.Generic;
using Umbraco.Core.Composing;
using Umbraco.Web.WebApi;
namespace TestCollections.Code
{
// Implement IDiscoverable (To help with typescanning speed/perf)
public interface IMyThing : IDiscoverable
{
string Name { get; }
string DoSomething(string message);
}
public class ExampleThing : IMyThing
{
public string Name => "Example";
public string DoSomething(string message)
{
return $"Hello {message}";
}
}
// OrderedCollection - use when order of items is important (You may want to excute them in order)
// Different types of collections - https://our.umbraco.com/Documentation/Implementation/Composing/#types-of-collections
// For more reference take a look at the various collection builders we have in Umbraco Core such as 'DashboardCollectionBuilder'
public class MyThingsCollectionBuilder : OrderedCollectionBuilderBase<MyThingsCollectionBuilder, MyThingsCollection, IMyThing>
{
protected override MyThingsCollectionBuilder This => this;
}
public class MyThingsCollection : BuilderCollectionBase<IMyThing>
{
public MyThingsCollection(IEnumerable<IMyThing> items)
: base(items)
{ }
}
public static class WebCompositionExtensions
{
public static MyThingsCollectionBuilder MyThings(this Composition composition)
=> composition.WithCollectionBuilder<MyThingsCollectionBuilder>();
}
public class MyThingComposer : IUserComposer
{
public void Compose(Composition composition)
{
//Explicitly add to the collection a Type
composition.MyThings().Append<ExampleThing>();
// composition.MyThings().Append<AnotherThing>();
// composition.MyThings().Append<SomeOtherThing>();
// Add types from assemblies - be conscious of doing type scanning
// Adds to bootup time
// If you have to then ensure your Interface implements `IDiscoverable`
composition.MyThings().Append(composition.TypeLoader.GetTypes<IMyThing>());
}
}
public class SomeBackofficeApiController : UmbracoAuthorizedApiController
{
private MyThingsCollection _mythings;
public SomeBackofficeApiController()
{
}
public SomeBackofficeApiController(MyThingsCollection mythings)
{
_mythings = mythings;
}
public List<string> GetMessages(string message)
{
var items = new List<string>();
foreach(var thing in _mythings)
{
items.Add(thing.DoSomething(message));
}
return items;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment