简体   繁体   中英

Interface not implemented with dependency injection

I have a simple counter app, to which I would like to add a metric by implementing a metrics interface, but I am receiving a not implemented exceptions when using the metric.

using System;
using Foo.Metrics; // This contains the interface "IFooMetrics" and class "MetricCounter"

namespace FooService
{
    class Program
    {
        private static MetricCounter _myMetric;

        public Program(IFooMetrics fooMetrics)
        {
            _myMetric = fooMetrics.CreateMetric();
        }

        static void Main(string[] args)
        {
            var counter = 0;
            var max = args.Length != 0 ? Convert.ToInt32(args[0]) : -1;

            while (max == -1 || counter < max)
            {
                counter++;
                Console.WriteLine($"Counter: {counter}");

                _myMetric.AddToCounter();
                Console.WriteLine("Metric added");

                System.Threading.Tasks.Task.Delay(1000).Wait();
            }
        }
    }
}

Unfortunately my knowledge of Dependency Injection is little, so I don't understand why its not working.

I simply want this metric to be initialized properly, but I am not sure what I'm not doing or doing wrong.

Use simple injector nuget package for example is easy .This is the documentation for simple injector simple injector doc

and here is a simple example example

First of all you must create the class MetricCounter which implement the interface IFooMetrics. Then create a container which register in the class with the interface as the example

private static readonly Container container;



static Program()
{
    container = new Container();

    container.Register<IFooMetrics, MetricCounter >();


    container.Verify();
}

and then in main

var service = container.GetInstance<IFooMetrics>();
service.YourMethod();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM