npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

com.cmdexecutor.dotnet-generic-host

v3.0.3

Published

.NET Generic Host (Microsoft.Extensions.Hosting) DI container adapted for Unity, works with IL2CPP.

Downloads

11

Readme

Preview

Twitter Follow

.NET Generic Host for Unity3D

This package allows to use DI Hosting (Microsoft.Extensions.Hosting) in Unity projects.

The documentation can be found here: Tutorial: Use dependency injection in .NET

Install

By git URL:

Add https://github.com/amelkor/Microsoft.Extensions.Hosting.Unity.git?path=Packages/com.cmdexecutor.dotnet-generic-host to Unity Package Manager

Or add "com.cmdexecutor.dotnet-generic-host": "https://github.com/amelkor/Microsoft.Extensions.Hosting.Unity.git?path=Packages/com.cmdexecutor.dotnet-generic-host" to Packages/manifest.json.

By OpenUPM

The package is available on the openupm registry. It's recommended to install it via openupm-cli.

openupm add com.cmdexecutor.dotnet-generic-host

Or add scoped registry to Packages/manifest.json

    "scopedRegistries": [
        {
            "name": "package.openupm.com",
            "url": "https://package.openupm.com",
            "scopes": [
                "com.cmdexecutor.dotnet-generic-host"
            ]
        }
    ],

By npmjs

Add scoped registry to Packages/manifest.json

    "scopedRegistries": [
        {
            "name": "npmjs.com",
            "url": "https://registry.npmjs.org",
            "scopes": [
                "com.cmdexecutor.dotnet-generic-host"
            ]
        }
    ],

Getting started

The repository contains demo Unity project.

Injection into Monobehaviour classes happens via custom defined private method which name is specified as Services Injection Method Name parameter in Inspector or ``. The default name is AwakeServices. Could be adjusted in the Unity Inspector window.

To get started, derive from HostManager and add the derived class to a GameObject on scene, that's mostly it.

    public class SampleHost : HostManager
    {
        [Tooltip("Could be used for referencing ScriptableObjects and as configuration provider")]
        [SerializeField] private ConfigurationScriptableObject configuration;
        
        [Tooltip("UI instance from scene of from SampleHost GameObject hierarchy")]
        [SerializeField] private SampleUI sampleUI;

        protected override void OnAwake()
        {
            // Awake called before host build
            // if buildOnAwake is false (can be controlled through Inspector) then host needs to be build manually
            // By default builds on Awake
            buildOnAwake = false;

            // Use custom methods name for Unity Objects (default is AwakeServices)
            // The services will be injected into ctor
            // servicesInjectionMethodName = "CustomInjectionMethodName";

            // Call from the desired place to build the host if buildOnAwake = false;
            BuildManually();

            // Stops the host
            // StopManually(); or StopManuallyAsync();
        }

        protected override void ConfigureAppConfiguration(HostBuilderContext context, IConfigurationBuilder builder)
        {
            Debug.Log("ConfigureAppConfiguration");
            
            // Add SO as configuration source, will parse all attributes from the SO and make them accessible from IConfiguration
            builder.AddScriptableObjectConfiguration<ConfigurationScriptableObject>(configuration);
        }

        protected override void ConfigureLogging(HostBuilderContext context, ILoggingBuilder builder)
        {
            Debug.Log("ConfigureLogging");
        }

        protected override void ConfigureServices(HostBuilderContext context, IServiceCollection services)
        {
            // Register ordinary C# classes
            Debug.Log("ConfigureServices");
        }

        protected override void ConfigureUnityObjects(HostBuilderContext context, IUnityObjectsConfigurator services)
        {
            Debug.Log("ConfigureUnityObjects");
            
            foreach (var (type, so) in configuration.GetScriptableObjectsToRegisterAsSingeltons())
                services.AddScriptableObjectSingleton(so, type);

            // Registers already instantiated instance under HostRoot GameObject
            services.AddMonoBehaviourSingleton(sampleUI);

            // Register as hosted service (will be resolved and start automatically when host start)
            services.AddMonoBehaviourHostedService<MonoHostedService>();

            // Creates new instances under HostRoot GameObject
            services.AddMonoBehaviourSingleton<MonoSingleton>();
            services.AddMonoBehaviourTransient<MonoTransient>();
            
            // Or creates new instance in scene root
            // services.AddDetachedMonoBehaviourSingleton<MonoSingleton>();

            Debug.Log($"SampleInteger config value from registered SO: {context.Configuration["SampleInteger"]}");
            
            // Loads from Resources (spawns detached)
            services.AddMonoBehaviourPrefabTransient<RandomMoveObject>(configuration.movingObjectPrefabName);
        }
    }

In case if Host needs to be composed manually, a minimal configuration could be similar to following:

            var hostBuilder = UnityHost.CreateDefaultBuilder(servicesInjectionMethodName, cmdArguments)
                .ConfigureAppConfiguration(builder =>
                {
                    builder.DisableFileConfigurationSourceReloadOnChange();
                    builder.AddCommandLine(cmdArguments);
                });
                .ConfigureLogging((_, loggingBuilder) =>
                {
                    loggingBuilder.SetMinimumLevel(logLevel);
                });
                .ConfigureUnityObjects((context, configurator) => {/*Add Mono services*/})
                .ConfigureServices(services =>
                {
                    services.AddSingleton<IMonoBehaviourHostRoot, MonoBehaviourHostRoot>(provider =>
                    {
                        var lifetime = provider.GetRequiredService<IHostApplicationLifetime>();

                        var root = new GameObject($"{nameof(MonoBehaviourHostRoot)} (host root)");
                        var component = root.AddComponent<MonoBehaviourHostRoot>();

                        lifetime.ApplicationStopped.Register(() =>
                        {
                            if (!root)
                                return;

                            UnityEngine.Object.Destroy(root.gameObject);
                        });

                        return component;
                    });
                });

            // add services
                // hostBuilder.ConfigureServices
                // hostBuilder.ConfigureMonoBehaviours

            // build the host
            var host = hostBuilder.Build();

            // start the host
            await host.StartAsync();

            // stop the host
            await host.StopAsync()

Licensing