Coder Social home page Coder Social logo

snowpowercore / microsoft.extensions.hosting.unity Goto Github PK

View Code? Open in Web Editor NEW

This project forked from amelkor/microsoft.extensions.hosting.unity

0.0 0.0 0.0 841 KB

.NET Generic Host adapted for Unity3D Microsoft.Extensions.Hosting

License: MIT License

C# 100.00%

microsoft.extensions.hosting.unity's Introduction

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

UPM Package install via npmjs:

Add the entry below to the project's manifest.json

    "scopedRegistries": [
      {
        "name": "microsoft.extensions.hosting",
        "url": "https://registry.npmjs.org",
        "scopes": [
          "com.blacksmallriver.hosting",
          "com.blacksmallriver"
        ]
      }
    ]

Or add it in Unity Editor:

Project Settings -> Package Manager -> Scoped Registries

name: microsoft.extensions.hosting

URL: https://registry.npmjs.org

scope: com.blacksmallriver.hosting

UPM Package install via git URL (no package updates will be available this way):

Requires a version of unity that supports path query parameter for git packages (Unity >= 2019.3.4f1).

Add https://github.com/amelkor/Microsoft.Extensions.Hosting.Unity.git to Unity Package Manager

Getting started

Check the Demo Project

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

To get started, you need to implement a HostManager

A new instance of Host could be created like:

            var hostBuilder = Host.CreateDefaultBuilder()
                .ConfigureLogging((_, loggingBuilder) => { loggingBuilder.ClearProviders(); })
                .UseMonoBehaviourServiceCollection(/*Services Injection Method Name for MonoBehaviour*/)
                .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()

loggingBuilder.ClearProviders(); is needed since DefaultHostBuilder uses some default logging stuff not available in Unity.

to log into Unity's console use hostBuilder.ConfigureLogging(builder => builder.AddUnityLogger());

Also there's a way to quickly setup a new Host via deriving from the default template MonoBehaviour class HostManager and attach it to a gameobject.

The settings are available through the Inspector window.

    /// <summary>
    /// Example implementation.
    /// </summary>
    public class DemoHostManager : HostManager
    {
        protected override void ConfigureAppConfiguration(IConfigurationBuilder builder)
        {
            // add a configuration providers here
        }

        protected override void ConfigureLogging(ILoggingBuilder builder)
        {
            // add a logger library here
        }

        protected override void ConfigureServices(IServiceCollection services)
        {
            // add ordinary C# classes services here
            
            // transient is also supported
            //services.AddTransient<JustService>();
            
            services.AddSingleton<JustService>();
            
            // hosted services could be added by their interfaces as well
            services.AddHostedService<IHostedServiceContract, PocHostedService>();
        }

        protected override void ConfigureMonoBehaviours(IMonoBehaviourServiceCollectionBuilder services)
        {
            // add MonoBehaviour classes services here
            // all MonoBehaviour singltones will be attached to a single gameObject created at runtime
            
            // transient will be created as new gameObject
            // services.AddMonoBehaviourTransient<DemoMono>();
            
            services.AddMonoBehaviourSingleton<DemoMono>();
            services.AddMonoBehaviourSingleton<BehaviourTestComponent>();
            
            // ScriptableObject's must be passed as an existing instance
            services.services.AddScriptableObjectSingleton(instance, typeof(MyScriptableObject));
            
            // a MonoBehaviour with IHostedService implementation
            services.AddMonoBehaviourHostedService<GameModeService>();
        }

Then create a new GameObject and attach the script.

GlobalSettings for Host

Inheriting from GlobalSettings class allows to have a settings file under Config/globalsettings.json path of the Unity application. Any property in the derived class would be saved into the file and read on the host starting.

Licensing

microsoft.extensions.hosting.unity's People

Contributors

amelkor avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.