Giter Club home page Giter Club logo

corerpc's Introduction

CoreRPC

Extensible library for WCF-like RPC targeting netstandard1.3 (compatible with .NET, Mono and .NET Core)

TCP transport supports connection pooling and multiplexing requests within one connection, infrastructure itself allows multiple "services" to be hosted inside one host. You may define your own handler factory or "routing" mechanism. Serializer (JSON.NET is used by default) is also easy to replace.

Protocol Definition

Put an interface into your shared library and reference it from both client and server apps.

public interface IService
{
    Task<string> Foo(int bar);
}

Server

Implement the declared interface.

public class Service : IService
{
    public Task<string> Foo(int bar)
    {
        return Task.FromResult(bar.ToString());
    }
}

Start your server using either TCP or HTTP protocol.

// TCP
var router = new DefaultTargetSelector();
router.Register<IService, Service>();
var host = new TcpHost(new Engine().CreateRequestHandler(router));
host.StartListening(new IPEndPoint(IPAddress.Loopback, 9000));
    
// ASP.NET Core (HTTP)
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    var router = new DefaultTargetSelector();
    router.Register<IService, Service>();
    app.UseCoreRPC("/rpc", new Engine().CreateRequestHandler(router));
}

// Named Pipes
var router = new DefaultTargetSelector();
router.Register<IService, Service>();
var host = new NamedPipeHost(new Engine().CreateRequestHandler(router));
host.StartListening("AwesomePipeName");

Client

Use the protocol your server uses and call remote procedures!

// TCP
var transport = new TcpClientTransport(IPAddress.Parse("127.0.0.1"));
var proxy = new Engine().CreateProxy<IService>(transport, 9000);

// HTTP 
var transport = new HttpClientTransport("http://example.com/rpc");
var proxy = new Engine().CreateProxy<IService>(transport);
var res = await proxy.Foo(1);

// Named Pipes
var transport = new NamedPipeClientTransport("AwesomePipeName");
var proxy = new Engine().CreateProxy<IService>(transport);

Assembly Scanning

CoreRPC.AspNetCore package supports automatic RPC registration. All you need is marking classes with RegisterRpc attribute. Classes marked with that attribute will get registered automatically once you add a call to .UseCoreRpc() to your app builder:

// Implement the shared interface.
[RegisterRpc(typeof(IService))]
public class Service : IService
{
    public Task<string> Foo(int bar)
    {
        return Task.FromResult(bar.ToString());
    }
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // CoreRPC will register the class maked with RegisterRpc 
    // attribute automagically.
    app.UseCoreRpc("/rpc");
}

You can override the built-in assembly scanning engine and some other options if necessary:

// This may be useful when writing integrational tests, etc.
app.UseCoreRpc("/rpc", config => 
{
    // By default, CoreRPC uses camel case resolver, but you can override that.
    config.JsonSerializer.ContractResolver = new DefaultContractResolver();
    config.RpcTypeResolver = () =>
    {
        // Skip abstract classes and types not marked with [RegisterRpc] (default behavior).
        var assembly = Assembly.GetAssembly(typeof(Startup));
        return assembly.DefinedTypes
            .Where(type => !type.IsAbstract || type.IsInterface && 
                   type.GetCustomAttribute<RegisterRpcAttribute>() != null);
    };
    
    // You can also add a custom RPC method call interceptor.
    config.Interceptors.Add(new MyMethodCallInterceptor());
});

RPC Interception

If you need to intercept RPCs, implement the IMethodCallInterceptor interface and register it:

// The simplest interceptor that apparently does nothing.
public class Interceptor : IMethodCallInterceptor
{
    public Task<object> Intercept(MethodCall call, object context, Func<Task<object>> invoke)
    {
        // Add your custom logic here.
        return invoke();
    }
}

// Register the method call interceptor.
app.UseCoreRpc("/rpc", config => config.Interceptors.Add(new Interceptor()));

TypeScript API Generation

CoreRPC provides you an ability to generate TypeScript code for your server-side API.

// Store the generated TS code somewhere, e.g. save it to 'api.ts' file.
// Putting such C# code into your Startup.cs file might be a good idea.
string generatedCode = AspNetCoreRpcTypescriptGenerator.GenerateCode(types, config =>
{
    config.ApiFieldNamingPolicy = type => type.Replace("Rpc", string.Empty);
    config.DtoFieldNamingPolicy = TypescriptGenerationOptions.ToCamelCase;
});

Usage Examples

See tests for more examples.

corerpc's People

Contributors

kekekeks avatar worldbeater avatar

Watchers

James Cloos avatar  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.