“They say that genius is an infinite capacity for taking pains,” he [Holmes] remarked with a smile. “It’s a very bad definition, but it does apply to detective work.”

Arthur Conan Doyle (1859-1930) British writer and physician
Story (1886-04), “A Study in Scarlet,” Part 1, ch. 3, Beeton’s Christmas Annual, Vol. 28 (1887-11-21)
    (Source)

Published in novel form 1888-07.

The quotation is usually attributed to Scottish historian and essayist Thomas Carlyle, but is a misquote of what he says on the subject, in his History of Frederick the Great [Friedrich the Second], Vol. 1, Book 4, ch. 3 (1858–65) (emphasis mine):

The good plan itself, this comes not of its own accord; it is the fruit of "genius" (which means transcendent capacity of taking trouble, first of all); given a huge stack of tumbled thrums, it is not in your sleep that you will find the vital centre of it, or get the first thrum by the end!

Thrums, by the way, are the ends of the warp threads in a loom which remain unwoven attached to the loom when the web is cut, or more loosely a collection of leftover thread or yarn.

The "infinite capacity" phrase is sometimes misattributed to Samuel Johnson.

See more discussion here.

Interestingly, Holmes, in the same story, earlier claims not to know Carlyle's works, though he here supposedly quotes him.