Thursday 26 April 2018

Case of dependency resolvers :)

If you ever have a situation where you have to mix few of the Web based technologies in single solution, you would start to wonder why these different technologies have their own way of dealing with Dependency Injection and IoC containers.

For example:

MVC 5

Well, ASP.NET MVC5 has its own namespaces and DependencyResolver instances that can be updated. You can find examples here

ASP.NET Core

You need to use a different infrastructure ("Services") to inject and resolve the dependencies.

Web API

As per WebAPI documentation, you need to implement your own resolver by implementing IDependecyResolver interface available under System.Web.Http.Dependencies namespace. You can then replace the default resolver with your resolver by updating the instance of HttpConfiguration used by WebAPI.


SignalR

As per SignalR documentation, it is to be done through a static class called GlobalHost. It exposes the SignalR related DependencyResolver as a property and we can use that to register types so that SignalR related objects can be automagically be created.

public void Configuration(IAppBuilder app)
{
    GlobalHost.DependencyResolver.Register(
        typeof(ChatHub), 
        () => new ChatHub(new ChatMessageRepository()));
}

There is a interface IDependencyResolver too under its own dedicated namespace which can be used to write own resolver and assign the same to HubConfiguration class during start up. However, recommended way is to inherit from DefaultDependencyResolver and add custom logic - this is because DefaultDependencyResolver takes care of resolving SignalR related infrastructure.

Friday 20 April 2018

wcf instance provider

Ever tried applying dependency injection container concepts in a WCF service? Well, you might say that not many people use WCF these days as majority of services are moving towards REST WebAPI. While that is true, it is also true that WCF gives us features and capabilities that a REST WebAPI has no support of. Anyhow, there is not much value to fight the urge to write a good WCF service with a decent DI logic.

All you have to do is to write an implementation of IInstanceProvider and apply a custom implementation of IServiceBehavior to the service.

IServiceBehavior:

public class CustomInstanceProviderBehaviorAttribute : Attribute, IServiceBehavior
    {
        public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection endpoints, BindingParameterCollection bindingParameters)
        {
        }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            foreach (ChannelDispatcher cd in serviceHostBase.ChannelDispatchers)
            {
                foreach (EndpointDispatcher ed in cd.Endpoints)
                {
                    if (!ed.IsSystemEndpoint)
                    {
                        ed.DispatchRuntime.InstanceProvider = new DIInstanceProvider(DateTime.UtcNow.Ticks);
                    }
                }
            }
        }

        public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
        }

    }

IInstanceProvider

public class DIInstanceProvider : IInstanceProvider
    {
        private long ticks = 0L;

        public DIInstanceProvider(long ticksValue)
        {
            this.ticks = ticksValue;
        }

        public object GetInstance(InstanceContext instanceContext)
        {
            return new Service1(DateTime.UtcNow.Ticks);
        }

        public object GetInstance(InstanceContext instanceContext, Message message)
        {
            return new Service1(DateTime.UtcNow.Ticks);
        }

        public void ReleaseInstance(InstanceContext instanceContext, object instance)
        {
        }

    }

Service
    [CustomInstanceProviderBehavior]
    public class Service1 : IService1
    {
        private long ticks = 0L;

        public Service1(long ticks)
        {
            this.ticks = ticks;
        }

        public string GetData(int value)
        {
            return string.Format("You entered: {0} at {1}", value, this.ticks);

        }
     }

Point to note: Instance of IInstanceProvider is created only once when service starts and applies the service behavior. However the service instance is created by calling GetInstance method of IInstanceProvider.

Wednesday 18 April 2018

Story Points : That elusive concept

I was recently involved in a meeting with a team that wanted to change story points of a User Story that they committed to deliver in the middle of the sprint. As much weird as it sounds, it did happen though and I was there. 

My first reaction was : Why?

Story points are a way of estimating the overall size of the User Story - Size includes effort, complexity and uncertainty. So if, during the implementation of the User Story, the team finds out that they estimated the size incorrectly (any of the 3 parts could have been wrongly estimated), teams should drop the User Story from current sprint and send it back to the backlog for further refinement. 
The reason is two folds:

1. Team is not good at estimating size.
2. User Story authors left too many things open to interpretation and team ignored those signs during story pint estimation

How can you try to address it?

1. Spend first 2-3 sprints in defining (or identifying) the User Stories that can be referred in later sprints. In the end, no estimation should be by gut feeling. There has to be verified baseline to work with. Most of the teams I have worked with forget to do this.

2. Prepare User Story structure in which scope of open ended specification is less. For Example: A Use story for a web page that has a grid needs to mention following - default sorting order, can user sort, default paging size, can user change page size, does grid have to refresh in place or are we ok to reload the page, Is the grid readonly or will user be able to update/delete/add a row, will grid hide columns if user resizes the page, will grid have its own scrollbar etc. In the end team needs to sets standards in terms of accepting a User Stories and things will follow.



Friday 13 April 2018

Self hosting vs IIS hosting

Imagine that you have a requirement to have a web API that supports hosting in both IIS and a windows service (an example of self hosting).

If you use OWIN and ASP.NET then it is not very difficult. In fact if you build one application using OWIN, you can host it in multiple ways. We will try IIS-Express and Console App. Let us start.

1. Create a new Web Application. Choose Empty template.



2. Use nuget package "Microsoft.Owin.Host.SystemWeb" and "Microsoft.AspNet.WebApi.Owin".
3. Use "OWIN Startup" class.


4. Change Startup.cs.

public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
            var config = new HttpConfiguration();

            config.Routes.MapHttpRoute(
                "API Default", "api/{controller}/{id}",
                new { id = RouteParameter.Optional });

            app.UseWebApi(config);
        }
    }

5. Add a test controller e.g. ValuesController like following.



5. Test the url.



Now that web application is up, let us see how easily we can host the same application in an Console application and not duplicate the code.

1. Add a console application. Add reference of the web application in console application.

2. Add nuget package "Microsoft.AspNet.WebApi.OwinSelfHost".
3. Change Program.cs to following.

static void Main(string[] args)
        {
            using (var x = WebApp.Start(url: "http://locahost:9000/"))
            {
                Console.WriteLine("Started");
                Console.ReadLine();
            }

        }

4. Launch console app and access "http://localhost:9000/api/values".


Have fun.

Thursday 5 April 2018

Architect musing: Where do you separate yourself from development team?

I have recently changed the official role in my company where i moved into an Architect role. After spending few days with my new project team, I started to ask where does the role of an Architect start and end and if a team needs an architect in the first place.

Here is what my opinion is:

Architect takes care of:

1. Look at business requirements and convert to technical requirements. Assist the BA team to ensure technical User Stories are created to support n+2 business related User Stories.
2. Know the big picture and be able to think how it can be built over the course of sprints.
3. Identify critical scenarios for team to take care as non-negotiable.
4. Work on tools/methods that can reduce development/testing/troubleshooting time
5. Work on non functional requirements and ensure that they are addressed by team
6. Manage techical debt/architecture debt
7. Implement/suggest patterns for implementation 
8. Be able to troubleshoot bugs
9. Ensure right technology is picked


Dev Lead takes care of:

1. Right skilled folks are part of team and work assignment is appropriate
2. Know if a certain work can fit within sprint
3. Ensure development is as per the provided specification
4. Be able to troubleshoot bugs/issues
5. Ensure team has enough tests to identify any regression issues
6. Ensure that technology is used in best possible way
7. Code is optimized and following agreed standards/practices
8. Team is not overloaded and is motivated
9. Team knows what is to come in current and next 2 sprints