欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

动手造*:实现一个简单的依赖注入(一)

程序员文章站 2023-01-13 13:01:24
动手造*:实现一个简单的依赖注入(一) Intro 在上一篇文章中主要介绍了一下要做的依赖注入的整体设计和大概编程体验,这篇文章要开始写代码了,开始实现自己的依赖注入框架。 类图 首先来温习一下上次提到的类图 服务生命周期 服务生命周期定义: 服务定义 服务注册定义: 为了使用起来更方便添加了一些 ......

动手造*:实现一个简单的依赖注入(一)

intro

在上一篇文章中主要介绍了一下要做的依赖注入的整体设计和大概编程体验,这篇文章要开始写代码了,开始实现自己的依赖注入框架。

类图

首先来温习一下上次提到的类图

动手造*:实现一个简单的依赖注入(一)

服务生命周期

服务生命周期定义:

public enum servicelifetime : sbyte
{
    /// <summary>
    /// specifies that a single instance of the service will be created.
    /// </summary>
    singleton = 0,

    /// <summary>
    /// specifies that a new instance of the service will be created for each scope.
    /// </summary>
    scoped = 1,

    /// <summary>
    /// specifies that a new instance of the service will be created every time it is requested.
    /// </summary>
    transient = 2,
}

服务定义

服务注册定义:

public class servicedefinition
{
    // 服务生命周期
    public servicelifetime servicelifetime { get; }
    // 实现类型
    public type implementtype { get; }
    // 服务类型
    public type servicetype { get; }
    // 实现实例
    public object implementationinstance { get; }
    // 实现工厂
    public func<iserviceprovider, object> implementationfactory { get; }

    // 获取真实的实现类型
    public type getimplementtype()
    {
        if (implementationinstance != null)
            return implementationinstance.gettype();

        if (implementationfactory != null)
            return implementationfactory.method.declaringtype;

        if (implementtype != null)
            return implementtype;

        return servicetype;
    }

    public servicedefinition(object instance, type servicetype)
    {
        implementationinstance = instance;
        servicetype = servicetype;
        servicelifetime = servicelifetime.singleton;
    }

    public servicedefinition(type servicetype, servicelifetime servicelifetime) : this(servicetype, servicetype, servicelifetime)
    {
    }

    public servicedefinition(type servicetype, type implementtype, servicelifetime servicelifetime)
    {
        servicetype = servicetype;
        implementtype = implementtype ?? servicetype;
        servicelifetime = servicelifetime;
    }

    public servicedefinition(type servicetype, func<iserviceprovider, object> factory, servicelifetime servicelifetime)
    {
        servicetype = servicetype;
        implementationfactory = factory;
        servicelifetime = servicelifetime;
    }
}

为了使用起来更方便添加了一些静态方法

public static servicedefinition singleton<tservice>(func<iserviceprovider, object> factory)
{
    return new servicedefinition(typeof(tservice), factory, servicelifetime.singleton);
}

public static servicedefinition scoped<tservice>(func<iserviceprovider, object> factory)
{
    return new servicedefinition(typeof(tservice), factory, servicelifetime.scoped);
}

public static servicedefinition transient<tservice>(func<iserviceprovider, object> factory)
{
    return new servicedefinition(typeof(tservice), factory, servicelifetime.transient);
}

public static servicedefinition singleton<tservice>()
{
    return new servicedefinition(typeof(tservice), servicelifetime.singleton);
}

public static servicedefinition scoped<tservice>()
{
    return new servicedefinition(typeof(tservice), servicelifetime.scoped);
}

public static servicedefinition transient<tservice>()
{
    return new servicedefinition(typeof(tservice), servicelifetime.transient);
}

public static servicedefinition singleton<tservice, tserviceimplement>() where tserviceimplement : tservice
{
    return new servicedefinition(typeof(tservice), typeof(tserviceimplement), servicelifetime.singleton);
}

public static servicedefinition scoped<tservice, tserviceimplement>() where tserviceimplement : tservice
{
    return new servicedefinition(typeof(tservice), typeof(tserviceimplement), servicelifetime.scoped);
}

public static servicedefinition transient<tservice, tserviceimplement>() where tserviceimplement : tservice
{
    return new servicedefinition(typeof(tservice), typeof(tserviceimplement), servicelifetime.transient);
}

servicecontainer

servicecontainer v1

public class servicecontainer : iservicecontainer
{
    internal readonly list<servicedefinition> _services;

    private readonly concurrentdictionary<type, object> _singletoninstances;

    private readonly concurrentdictionary<type, object> _scopedinstances;
    
    private readonly list<object> _transientdisposables = new list<object>();

    private readonly bool _isrootscope;

    public servicecontainer()
    {
        _isrootscope = true;
        _singletoninstances = new concurrentdictionary<type, object>();
        _services = new list<servicedefinition>();
    }

    internal servicecontainer(servicecontainer servicecontainer)
    {
        _isrootscope = false;
        _singletoninstances = servicecontainer._singletoninstances;
        _services = servicecontainer._services;
        _scopedinstances = new concurrentdictionary<type, object>();
    }

    public void add(servicedefinition item)
    {
        _services.add(item);
    }

    public iservicecontainer createscope()
    {
        return new servicecontainer(this);
    }

    private bool _disposed;

    public void dispose()
    {
        if (_disposed)
        {
            return;
        }

        if (_isrootscope)
        {
            lock (_singletoninstances)
            {
                if (_disposed)
                {
                    return;
                }

                _disposed = true;
                foreach (var instance in _singletoninstances.values)
                {
                    (instance as idisposable)?.dispose();
                }

                foreach (var o in _transientdisposables)
                {
                    (o as idisposable)?.dispose();
                }
            }
        }
        else
        {
            lock (_scopedinstances)
            {
                if (_disposed)
                {
                    return;
                }

                _disposed = true;
                foreach (var instance in _scopedinstances.values)
                {
                    (instance as idisposable)?.dispose();
                }

                foreach (var o in _transientdisposables)
                {
                    (o as idisposable)?.dispose();
                }
            }
        }
    }

    private object getserviceinstance(type servicetype, servicedefinition servicedefinition)
    {
        if (servicedefinition.implementationinstance != null)
            return servicedefinition.implementationinstance;

        if (servicedefinition.implementationfactory != null)
            return servicedefinition.implementationfactory.invoke(this);

        var implementtype = (servicedefinition.implementtype ?? servicetype);

        if (implementtype.isinterface || implementtype.isabstract)
        {
            throw new invalidoperationexception($"invalid service registered, servicetype: {servicetype.fullname}, implementtype: {servicedefinition.implementtype}");
        }

        var ctorinfos = implementtype.getconstructors(bindingflags.instance | bindingflags.public);
        if (ctorinfos.length == 0)
        {
            throw new invalidoperationexception($"service {servicetype.fullname} does not have any public constructors");
        }

        constructorinfo ctor;
        if (ctorinfos.length == 1)
        {
            ctor = ctorinfos[0];
        }
        else
        {
            // try find best ctor
            ctor = ctorinfos
                .orderby(_ => _.getparameters().length)
                .first();
        }

        var parameters = ctor.getparameters();
        if (parameters.length == 0)
        {
            // todo: cache new func
            return expression.lambda<func<object>>(expression.new(ctor)).compile().invoke();
        }
        else
        {
            var ctorparams = new object[parameters.length];
            for (var index = 0; index < parameters.length; index++)
            {
                var parameter = parameters[index];
                var param = getservice(parameter.parametertype);
                if (param == null && parameter.hasdefaultvalue)
                {
                    param = parameter.defaultvalue;
                }

                ctorparams[index] = param;
            }
            return expression.lambda<func<object>>(expression.new(ctor, ctorparams.select(expression.constant))).compile().invoke();
        }
    }

    public object getservice(type servicetype)
    {
        var servicedefinition = _services.lastordefault(_ => _.servicetype == servicetype);
        if (null == servicedefinition)
        {
            return null;
        }

        if (_isrootscope && servicedefinition.servicelifetime == servicelifetime.scoped)
        {
            throw new invalidoperationexception($"can not get scope service from the root scope, servicetype: {servicetype.fullname}");
        }

        if (servicedefinition.servicelifetime == servicelifetime.singleton)
        {
            var svc = _singletoninstances.getoradd(servicetype, (t) => getserviceinstance(t, servicedefinition));
            return svc;
        }
        else if (servicedefinition.servicelifetime == servicelifetime.scoped)
        {
            var svc = _scopedinstances.getoradd(servicetype, (t) => getserviceinstance(t, servicedefinition));
            return svc;
        }
        else
        {
            var svc = getserviceinstance(servicetype, servicedefinition);
            if (svc is idisposable)
            {
                _transientdisposables.add(svc);
            }
            return svc;
        }
    }
}

为了使得服务注册更加方便,可以写一些扩展方法来方便注册:

public static iservicecontainer addsingleton<tservice>([notnull]this iservicecontainer servicecontainer, [notnull]tservice service)
{
    servicecontainer.add(new servicedefinition(service, typeof(tservice)));
    return servicecontainer;
}

public static iservicecontainer addsingleton([notnull]this iservicecontainer servicecontainer, [notnull]type servicetype)
{
    servicecontainer.add(new servicedefinition(servicetype, servicelifetime.singleton));
    return servicecontainer;
}

public static iservicecontainer addsingleton([notnull]this iservicecontainer servicecontainer, [notnull]type servicetype, [notnull]type implementtype)
{
    servicecontainer.add(new servicedefinition(servicetype, implementtype, servicelifetime.singleton));
    return servicecontainer;
}

public static iservicecontainer addsingleton<tservice>([notnull]this iservicecontainer servicecontainer, [notnull]func<iserviceprovider, object> func)
{
    servicecontainer.add(servicedefinition.singleton<tservice>(func));
    return servicecontainer;
}


public static iservicecontainer addsingleton<tservice>([notnull]this iservicecontainer servicecontainer)
{
    servicecontainer.add(servicedefinition.singleton<tservice>());
    return servicecontainer;
}


public static iservicecontainer addsingleton<tservice, tserviceimplement>([notnull]this iservicecontainer servicecontainer) where tserviceimplement : tservice
{
    servicecontainer.add(servicedefinition.singleton<tservice, tserviceimplement>());
    return servicecontainer;
}

public static iservicecontainer addscoped([notnull]this iservicecontainer servicecontainer, [notnull]type servicetype)
{
    servicecontainer.add(new servicedefinition(servicetype, servicelifetime.scoped));
    return servicecontainer;
}

public static iservicecontainer addscoped([notnull]this iservicecontainer servicecontainer, [notnull]type servicetype, [notnull]type implementtype)
{
    servicecontainer.add(new servicedefinition(servicetype, implementtype, servicelifetime.scoped));
    return servicecontainer;
}

public static iservicecontainer addscoped<tservice>([notnull]this iservicecontainer servicecontainer, [notnull]func<iserviceprovider, object> func)
{
    servicecontainer.add(servicedefinition.scoped<tservice>(func));
    return servicecontainer;
}


public static iservicecontainer addscoped<tservice>([notnull]this iservicecontainer servicecontainer)
{
    servicecontainer.add(servicedefinition.scoped<tservice>());
    return servicecontainer;
}


public static iservicecontainer addscoped<tservice, tserviceimplement>([notnull]this iservicecontainer servicecontainer) where tserviceimplement : tservice
{
    servicecontainer.add(servicedefinition.scoped<tservice, tserviceimplement>());
    return servicecontainer;
}

public static iservicecontainer addtransient([notnull]this iservicecontainer servicecontainer, [notnull]type servicetype)
{
    servicecontainer.add(new servicedefinition(servicetype, servicelifetime.transient));
    return servicecontainer;
}

public static iservicecontainer addtransient([notnull]this iservicecontainer servicecontainer, [notnull]type servicetype, [notnull]type implementtype)
{
    servicecontainer.add(new servicedefinition(servicetype, implementtype, servicelifetime.transient));
    return servicecontainer;
}

public static iservicecontainer addtransient<tservice>([notnull]this iservicecontainer servicecontainer, [notnull]func<iserviceprovider, object> func)
{
    servicecontainer.add(servicedefinition.transient<tservice>(func));
    return servicecontainer;
}


public static iservicecontainer addtransient<tservice>([notnull]this iservicecontainer servicecontainer)
{
    servicecontainer.add(servicedefinition.transient<tservice>());
    return servicecontainer;
}


public static iservicecontainer addtransient<tservice, tserviceimplement>([notnull]this iservicecontainer servicecontainer) where tserviceimplement : tservice
{
    servicecontainer.add(servicedefinition.transient<tservice, tserviceimplement>());
    return servicecontainer;
}

通过上面的代码就可以实现基本依赖注入了,但是从功能上来说,上面的代码只支持获取单个服务的实例,不支持注册一个接口的多个实现,获取接口的所有实现,为此对 servicecontainer 中的 instance 的 concurrentdictionary 的 key 进行一下改造,使得可以能够以接口类型和实现类型联合作为 key,为此就有了第二版的 servicecontainer

servicecontainer v2

为此定义了一个 servicekey 的类型,请注意这里一定要重写 gethashcode 方法:

private class servicekey : iequatable<servicekey>
{
    public type servicetype { get; }

    public type implementtype { get; }

    public servicekey(type servicetype, servicedefinition definition)
    {
        servicetype = servicetype;
        implementtype = definition.getimplementtype();
    }

    public bool equals(servicekey other)
    {
        return servicetype == other?.servicetype && implementtype == other?.implementtype;
    }

    public override bool equals(object obj)
    {
        return equals((servicekey)obj);
    }

    public override int gethashcode()
    {
        var key = $"{servicetype.fullname}_{implementtype.fullname}";
        return key.gethashcode();
    }
}

第二版的 servicecontainer :

public class servicecontainer : iservicecontainer
{
    internal readonly concurrentbag<servicedefinition> _services;

    private readonly concurrentdictionary<servicekey, object> _singletoninstances;

    private readonly concurrentdictionary<servicekey, object> _scopedinstances;
    private concurrentbag<object> _transientdisposables = new concurrentbag<object>();

    private class servicekey : iequatable<servicekey>
    {
        public type servicetype { get; }

        public type implementtype { get; }

        public servicekey(type servicetype, servicedefinition definition)
        {
            servicetype = servicetype;
            implementtype = definition.getimplementtype();
        }

        public bool equals(servicekey other)
        {
            return servicetype == other?.servicetype && implementtype == other?.implementtype;
        }

        public override bool equals(object obj)
        {
            return equals((servicekey)obj);
        }

        public override int gethashcode()
        {
            var key = $"{servicetype.fullname}_{implementtype.fullname}";
            return key.gethashcode();
        }
    }

    private readonly bool _isrootscope;

    public servicecontainer()
    {
        _isrootscope = true;
        _singletoninstances = new concurrentdictionary<servicekey, object>();
        _services = new concurrentbag<servicedefinition>();
    }

    private servicecontainer(servicecontainer servicecontainer)
    {
        _isrootscope = false;
        _singletoninstances = servicecontainer._singletoninstances;
        _services = servicecontainer._services;
        _scopedinstances = new concurrentdictionary<servicekey, object>();
    }

    public iservicecontainer add(servicedefinition item)
    {
        if (_disposed)
        {
            throw new invalidoperationexception("the service container had been disposed");
        }
        if (_services.any(_ => _.servicetype == item.servicetype && _.getimplementtype() == item.getimplementtype()))
        {
            return this;
        }

        _services.add(item);
        return this;
    }

    public iservicecontainer tryadd(servicedefinition item)
    {
        if (_disposed)
        {
            throw new invalidoperationexception("the service container had been disposed");
        }
        if (_services.any(_ => _.servicetype == item.servicetype))
        {
            return this;
        }
        _services.add(item);
        return this;
    }

    public iservicecontainer createscope()
    {
        return new servicecontainer(this);
    }

    private bool _disposed;

    public void dispose()
    {
        if (_disposed)
        {
            return;
        }

        if (_isrootscope)
        {
            lock (_singletoninstances)
            {
                if (_disposed)
                {
                    return;
                }

                _disposed = true;
                foreach (var instance in _singletoninstances.values)
                {
                    (instance as idisposable)?.dispose();
                }

                foreach (var o in _transientdisposables)
                {
                    (o as idisposable)?.dispose();
                }

                _singletoninstances.clear();
                _transientdisposables = null;
            }
        }
        else
        {
            lock (_scopedinstances)
            {
                if (_disposed)
                {
                    return;
                }

                _disposed = true;
                foreach (var instance in _scopedinstances.values)
                {
                    (instance as idisposable)?.dispose();
                }

                foreach (var o in _transientdisposables)
                {
                    (o as idisposable)?.dispose();
                }

                _scopedinstances.clear();
                _transientdisposables = null;
            }
        }
    }

    private object getserviceinstance(type servicetype, servicedefinition servicedefinition)
    {
        if (servicedefinition.implementationinstance != null)
            return servicedefinition.implementationinstance;

        if (servicedefinition.implementationfactory != null)
            return servicedefinition.implementationfactory.invoke(this);

        var implementtype = (servicedefinition.implementtype ?? servicetype);

        if (implementtype.isinterface || implementtype.isabstract)
        {
            throw new invalidoperationexception($"invalid service registered, servicetype: {servicetype.fullname}, implementtype: {servicedefinition.implementtype}");
        }

        if (implementtype.isgenerictype)
        {
            implementtype = implementtype.makegenerictype(servicetype.getgenericarguments());
        }

        var ctorinfos = implementtype.getconstructors(bindingflags.instance | bindingflags.public);
        if (ctorinfos.length == 0)
        {
            throw new invalidoperationexception($"service {servicetype.fullname} does not have any public constructors");
        }

        constructorinfo ctor;
        if (ctorinfos.length == 1)
        {
            ctor = ctorinfos[0];
        }
        else
        {
            // todo: try find best ctor
            ctor = ctorinfos
                .orderby(_ => _.getparameters().length)
                .first();
        }

        var parameters = ctor.getparameters();
        if (parameters.length == 0)
        {
            // todo: cache new func
            return expression.lambda<func<object>>(expression.new(ctor)).compile().invoke();
        }
        else
        {
            var ctorparams = new object[parameters.length];
            for (var index = 0; index < parameters.length; index++)
            {
                var parameter = parameters[index];
                var param = getservice(parameter.parametertype);
                if (param == null && parameter.hasdefaultvalue)
                {
                    param = parameter.defaultvalue;
                }

                ctorparams[index] = param;
            }
            return expression.lambda<func<object>>(expression.new(ctor, ctorparams.select(expression.constant))).compile().invoke();
        }
    }

    public object getservice(type servicetype)
    {
        if (_disposed)
        {
            throw new invalidoperationexception($"can not get scope service from a disposed scope, servicetype: {servicetype.fullname}");
        }

        var servicedefinition = _services.lastordefault(_ => _.servicetype == servicetype);
        if (null == servicedefinition)
        {
            if (servicetype.isgenerictype)
            {
                var generictype = servicetype.getgenerictypedefinition();
                servicedefinition = _services.lastordefault(_ => _.servicetype == generictype);
                if (null == servicedefinition)
                {
                    var innerservicetype = servicetype.getgenericarguments().first();
                    if (typeof(ienumerable<>).makegenerictype(innerservicetype)
                        .isassignablefrom(servicetype))
                    {
                        var innerregtype = innerservicetype;
                        if (innerservicetype.isgenerictype)
                        {
                            innerregtype = innerservicetype.getgenerictypedefinition();
                        }
                        //
                        var list = new list<object>(4);
                        foreach (var def in _services.where(_ => _.servicetype == innerregtype))
                        {
                            object svc;
                            if (def.servicelifetime == servicelifetime.singleton)
                            {
                                svc = _singletoninstances.getoradd(new servicekey(innerservicetype, def), (t) => getserviceinstance(innerservicetype, def));
                            }
                            else if (def.servicelifetime == servicelifetime.scoped)
                            {
                                svc = _scopedinstances.getoradd(new servicekey(innerservicetype, def), (t) => getserviceinstance(innerservicetype, def));
                            }
                            else
                            {
                                svc = getserviceinstance(innerservicetype, def);
                                if (svc is idisposable)
                                {
                                    _transientdisposables.add(svc);
                                }
                            }
                            if (null != svc)
                            {
                                list.add(svc);
                            }
                        }

                        var methodinfo = typeof(enumerable)
                            .getmethod("cast", bindingflags.static | bindingflags.public);
                        if (methodinfo != null)
                        {
                            var genericmethod = methodinfo.makegenericmethod(innerservicetype);
                            var castedvalue = genericmethod.invoke(null, new object[] { list });
                            if (typeof(ienumerable<>).makegenerictype(innerservicetype) == servicetype)
                            {
                                return castedvalue;
                            }
                            var toarraymethod = typeof(enumerable).getmethod("toarray", bindingflags.static | bindingflags.public)
                                .makegenericmethod(innerservicetype);

                            return toarraymethod.invoke(null, new object[] { castedvalue });
                        }
                        return list;
                    }

                    return null;
                }
            }
            else
            {
                return null;
            }
        }

        if (_isrootscope && servicedefinition.servicelifetime == servicelifetime.scoped)
        {
            throw new invalidoperationexception($"can not get scope service from the root scope, servicetype: {servicetype.fullname}");
        }

        if (servicedefinition.servicelifetime == servicelifetime.singleton)
        {
            var svc = _singletoninstances.getoradd(new servicekey(servicetype, servicedefinition), (t) => getserviceinstance(t.servicetype, servicedefinition));
            return svc;
        }
        else if (servicedefinition.servicelifetime == servicelifetime.scoped)
        {
            var svc = _scopedinstances.getoradd(new servicekey(servicetype, servicedefinition), (t) => getserviceinstance(t.servicetype, servicedefinition));
            return svc;
        }
        else
        {
            var svc = getserviceinstance(servicetype, servicedefinition);
            if (svc is idisposable)
            {
                _transientdisposables.add(svc);
            }
            return svc;
        }
    }
}

这样我们就不仅支持了 ienumerable<tservice> 的注册,也支持 ireadonlylist<tservice>/ ireadonlycollection<tservice> 的注册

因为 getservice 返回是 object , 不是强类型的,所以为了使用起来方便,定义了几个扩展方法,类似于微软的依赖注入框架里的 getservice<tservice>()/getservices<tservice>()/getrequiredservice<tservice>()

/// <summary>
/// resolveservice
/// </summary>
/// <typeparam name="tservice">tservice</typeparam>
/// <param name="serviceprovider">serviceprovider</param>
/// <returns></returns>
public static tservice resolveservice<tservice>([notnull]this iserviceprovider serviceprovider)
    => (tservice)serviceprovider.getservice(typeof(tservice));

/// <summary>
/// resolverequiredservice
/// throw exception if can not get a service instance
/// </summary>
/// <typeparam name="tservice">tservice</typeparam>
/// <param name="serviceprovider">serviceprovider</param>
/// <returns></returns>
public static tservice resolverequiredservice<tservice>([notnull] this iserviceprovider serviceprovider)
{
    var servicetype = typeof(tservice);
    var svc = serviceprovider.getservice(servicetype);
    if (null == svc)
    {
        throw new invalidoperationexception($"service had not been registered, servicetype: {servicetype}");
    }
    return (tservice)svc;
}

/// <summary>
/// resolve services
/// </summary>
/// <typeparam name="tservice">tservice</typeparam>
/// <param name="serviceprovider">serviceprovider</param>
/// <returns></returns>
public static ienumerable<tservice> resolveservices<tservice>([notnull]this iserviceprovider serviceprovider)
    => serviceprovider.resolveservice<ienumerable<tservice>>();

more

后面还更新了一版,主要优化性能,目前来说还不太满意,暂时这里先不提了

reference